1

尝试使用 mediacontroller 通过 url 播放音频文件

但我得到错误:

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,它可以工作,因为如果我不实现媒体控制器,歌曲就会播放。代码很长,所以让我知道我需要添加哪一部分。

4

1 回答 1

0

我设法自己解决了它:

我添加了更多调试:

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

瞧!

于 2013-09-11T16:27:00.047 回答