-2

I am using MediaPlayer to playback audio file of .WAV format. When I debug the app I'm able to play file but when I run the app file is not playing.

There is a similar issue regarding this but no solution is provided.

Below is the code which i am using

MediaPlayer mMediaPlayer = new MediaPlayer();
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mMediaPlayer.setDataSource(mContext, fileUri);// uri of the audio file
mMediaPlayer.prepare();
mMediaPlayer.setOnCompletionListener(this);    
mMediaPlayer.start();// to start the playback of the audio file

This code is working only in debug mode but not in normal mode.

Thanks

Community
  • 1
  • 1
ravi
  • 2,722
  • 7
  • 25
  • 42
  • You need to add `mMediaPlayer.start();` in `onPreparedListener()` of `MediaPlayer`. – activesince93 Nov 16 '15 at 10:00
  • You are starting `MediaPlayer` before it is prepared. – activesince93 Nov 16 '15 at 10:01
  • And better to use `mMediaPlayer.prepareAsync();` rather than `mMediaPlayer.prepare();`. – activesince93 Nov 16 '15 at 10:02
  • @activesince93 thanks for your reply. I want to play audio file on button click so i cannot use mMediaPlayer.start(); in onPreparedListener(). I'm not starting mediaplayer before preparing it. – ravi Nov 16 '15 at 10:04
  • @ravi, Did you solved this issue? If yes then please share correct answer so that others get help to solve same problem. – anddev Mar 10 '16 at 09:12

1 Answers1

1

This is what I am saying:

btn_next.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        mp.setAudioStreamType(AudioManager.STREAM_MUSIC);

        try {
            mp.reset();
            mp.setDataSource(url.toString());
            mp.setOnErrorListener(this);
            mp.setOnPreparedListener(this);
            mp.setOnCompletionListener(this);
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            Log.e(TAG, "SecurityException");
        } catch (IllegalStateException e) {
            Log.e(TAG, "IllegalStateException");
        } catch (IOException e) {
            Log.e(TAG, "IOException");
        }
        mp.prepareAsync();
    }
});

Now, override method onPrepared().

@Override
public void onPrepared(MediaPlayer mp) {
    // TODO Auto-generated method stub
    mp.start();
}

Comment below if you face any issue in this.

activesince93
  • 1,716
  • 17
  • 37