Java 问题:准备MediaPlayer播放自定义文件

Java 问题:准备MediaPlayer播放自定义文件,java,android,android-mediaplayer,media,illegalstateexception,Java,Android,Android Mediaplayer,Media,Illegalstateexception,因此,当我播放应用程序包含在res/raw文件夹中的文件中的音频时,基本上一切正常,但当我希望用户选择自己的文件时,我遇到了麻烦 目标是将媒体播放器的数据源设置为用户所选文件的URI。然后使用新的数据源初始化播放器并播放它。调用play方法时会出现我的错误。它最后说我在一个非法状态下调用了play(也就是说,我没有事先为玩家做好准备),但它肯定已经准备好了。发生了什么,我如何修复它 调用方法以选择文件: public void chooseFile(){ Intent intent;

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

目标是将媒体播放器的数据源设置为用户所选文件的URI。然后使用新的数据源初始化播放器并播放它。调用play方法时会出现我的错误。它最后说我在一个非法状态下调用了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.");
    }

}

如果有帮助,请使用此选项:

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

在播放器上使用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();
    }
}