【问题标题】:Issue Preparing MediaPlayer to play custom file问题准备 MediaPlayer 播放自定义文件
【发布时间】:2014-04-24 04:36:38
【问题描述】:

所以当我从 res/raw 文件夹中的应用程序包含的文件中播放音频时,基本上一切正常,但是当我希望用户选择他们自己的文件时,我遇到了麻烦。

对象是将媒体播放器的数据源设置为用户所选文件的 URI。然后用新的数据源初始化播放器并播放它。调用 play 方法时出现我的错误。它最终说我在非法状态下调用游戏(即我没有事先准备球员)但它绝对是准备好的。发生了什么,我该如何解决?

选择文件的调用方法:

public void chooseFile(){
    Intent intent;
    intent = new Intent();
    intent.setAction(Intent.ACTION_GET_CONTENT);
    intent.setType("audio/mpeg");
    startActivityForResult(Intent.createChooser(intent, chosenAudioFilePath), 1);
}

活动结果方法:

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if(resultCode != RESULT_CANCELED){
    if (requestCode == 1 && resultCode == Activity.RESULT_OK){
        if ((data != null) && (data.getData() != null)){
            userChosenFilePath = data.getData();
            setSongToUserPick();

            }
        }
}}

setSongToUserPick 方法:

public void setSongToUserPick(){
    stop();
    currentAudioPath = userChosenFilePath;
    initializePlayer();
    stopped = false;
    play();
}

停止方法:

public void stop() {
    isPlaying = false;
    stopped = true;
    playPauseButton.setText("Play");
    player.stop();
    player.release();
}

初始化播放器方法:

public void initializePlayer() {


    nowPlayingView.setText(FilenameUtils.getBaseName(currentAudioPath.toString()));

    try {
        player.setDataSource(thisContext, currentAudioPath);
    } catch (IllegalArgumentException | SecurityException
            | IllegalStateException | IOException e) {
        e.printStackTrace();
    }
    try {
        player.prepare();
    } catch (IllegalStateException | IOException e) {
        e.printStackTrace();
    }

}

最后,播放方法:

public void play() {
    if(isPrepared){
    isPlaying = true;
    playPauseButton.setText("Pause");
    player.start();
    }else{
        System.out.println("Ahhh shit it broke.");
    }

}

【问题讨论】:

    标签: java android android-mediaplayer media illegalstateexception


    【解决方案1】:

    如果对您有帮助,请使用它:

    if(currentAudioPath!=null)
        player = MediaPlayer.create(thisContext, Uri.parse(currentAudioPath.toString()));
    

    【讨论】:

      【解决方案2】:

      在播放器上使用 onPreparedListener。您在其中使用 play() 方法。 还要在你的播放器上使用 onCompleteListener 因为现在发生的事情是 您所做的所有事情都是同时发生的,这就是导致问题的原因。

      public void play() {
              player.setOnCompletionListener(this);
              player.setOnPreparedListener(this);
              player.setDataSource(uri);
              player.prepareAsync();
      }
      
      
      @Override
      public void onPrepared(MediaPlayer mp) {
          if (!mp.isPlaying()) {
              mp.start();
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-04-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多