【发布时间】: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