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

问题描述 投票:1回答:2

因此,当我从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();

            }
        }
}}

Сесонготусерпицкметоход:

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
2个回答
0
投票

如果它可以帮助你,请使用它:

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

0
投票

在播放器上使用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();
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.