Audio file not playing with mediaController?

796 views Asked by At

Trying to play an audio file via url with mediacontroller

But I get error:

09-11 10:28:23.970: E/MediaPlayer(912): Attempt to call getDuration without a valid mediaplayer 09-11 10:28:23.970: E/MediaPlayer(912): error (-38, 0) 09-11 10:28:23.990: E/MediaPlayer(912): Attempt to perform seekTo in wrong state: mPlayer=0x5d425340, mCurrentState=0

I looked various answers here on SO, but did not solve. I try calling getDuration() in onPrepared()

mMediaPlayer = new MediaPlayer();
mMediaController = new MediaController(this);
mMediaController.setMediaPlayer(TextToSpeechActivity.this);
mMediaController.setAnchorView(findViewById(R.id.audioView));


try {
    mMediaPlayer.setDataSource(getSoundUrl());

    mMediaPlayer.prepare();
} catch (IOException e) {
    Log.e("PlayAudioDemo", "Could not open file  for playback.", e);
}

mMediaPlayer.setOnPreparedListener(new OnPreparedListener() {
    @Override
    public void onPrepared(MediaPlayer mp) {
            mHandler.post(new Runnable() {
                    public void run() {
                                           //did not help
                        int duration = mMediaPlayer.getDuration();
                            mMediaController.show(10000);
                            mMediaPlayer.start();
                    }
            });
    }
});

getSoundUrl() returns the URL to the soundfile(wav), it works because the song plays if I dont implement the media controller. Code is lengthy , so let me know which part I need to add.

1

There are 1 answers

0
meda On BEST ANSWER

I managed to solved it myslef:

I added more debugging:

try {
    mMediaPlayer.setDataSource(getSoundUrl());
    mMediaPlayer.prepare();

} catch (IllegalArgumentException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (SecurityException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (IllegalStateException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

Then instead of setting the listenner using setOnPreparedListener() I implemented OnPreparedListener in the Activity instead like this:

public class TextToSpeechActivity  
extends FragmentActivity implements MediaPlayerControl, OnPreparedListener  {

Then onPrepared():

public void onPrepared(MediaPlayer mediaPlayer) {
    Log.d("mylog", "onPrepared");
    mMediaController.setMediaPlayer(this);
    mMediaController.setAnchorView(findViewById(R.id.audioView));

    mHandler.post(new Runnable() {
      public void run() {

          mMediaController.setEnabled(true);
          mMediaController.show();
      }
    });
  }

and Voila!!