音频文件没有与mediaController一起播放?

时间:2013-09-11 15:26:20

标签: java android android-mediaplayer mediacontroller

尝试通过带有mediacontroller的网址播放音频文件

但我得到错误:

  

09-11 10:28:23.970:E / MediaPlayer(912):尝试调用getDuration   没有有效的媒体播放器09-11 10:28:23.970:E / MediaPlayer(912):   错误(-38,0)09-11 10:28:23.990:E / MediaPlayer(912):尝试   执行seekTo处于错误状态:mPlayer = 0x5d425340,mCu​​rrentState = 0

我在这里看了各种各样的答案,但没有解决。 我尝试在getDuration()

中拨打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()返回声音文件(wav)的URL,它起作用,因为如果我不实现媒体控制器,歌曲会播放。 代码很冗长,所以让我知道我需要添加哪个部分。

1 个答案:

答案 0 :(得分:0)

我设法解决了它myslef:

我添加了更多调试:

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();
}

然后我没有使用setOnPreparedListener()设置监听器,而是在Activity中实现了OnPreparedListener,而不是这样:

public class TextToSpeechActivity  
extends FragmentActivity implements MediaPlayerControl, OnPreparedListener  {

然后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();
      }
    });
  }

和Voila !!