Monther
Monther

Reputation: 31

Audio does not work in android studio (MediaPlayer)

I have a simple program in android studio with one button to play an audio file. However, the audio does not work when I press the button.

PS. I use the emulator

public class MainActivity extends AppCompatActivity {

    private MediaPlayer mediaPlayer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mediaPlayer = MediaPlayer.create(MainActivity.this, R.raw.out);

        Button play = (Button) findViewById(R.id.play_button);
        play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mediaPlayer.start();
            }
        });
    }

}

Upvotes: 0

Views: 1453

Answers (3)

ramya br
ramya br

Reputation: 225

Please try this.

MediaPlayer  mediaPlayer = Create(this, R.raw.out);
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);

Upvotes: 1

Karan Harsh Wardhan
Karan Harsh Wardhan

Reputation: 1126

mediaPlayer.reset();// stops any current playing song
mediaPlayer= MediaPlayer.create(getApplicationContext(), resourceID);
mediaPlayer.start(); // starting mediaplayer

another option is that instead of placing your file in raw folder you can just put it in the assets folder and play it using AssetManager

Upvotes: 0

bugfreerammohan
bugfreerammohan

Reputation: 1489

The problem is that the media volume is set to 0 (not the ringer volume). You can set it by:

AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 20, 0);

Upvotes: 0

Related Questions