我在旅途中生成 MIDI 文件。我想连续播放这些文件。
我初始化了一个媒体播放器并启动了 song1.mid。然后我用下面的代码播放song2.mid
// set on completion listener music file
mediaPlayer
.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
String filePath2 = null;
File file = null;
FileInputStream inputStream = null;
//set the filePath
try {
filePath2 = getCacheDir() + "/optimuse" + song + ".mid";
file = new File(filePath2);
if (file.exists()) {
inputStream = new FileInputStream(file);
if (inputStream.getFD().valid()) {
System.out.println("Valid!");
}
}
} catch (Exception e1) {
e1.printStackTrace();
System.exit(-1);
}
//set Mediaplayer's datasource
if (file.exists()) {
try {
mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(inputStream.getFD());
inputStream.close();
} catch (Exception e1) {
e1.printStackTrace();
System.exit(-1);
}
try {
mediaPlayer.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
//if the player is not running
if (!mediaPlayer.isPlaying()) {
//start the player
mediaPlayer.start();
Toast.makeText(MainActivity.this,
"mediaPlayer.start()", Toast.LENGTH_LONG)
.show();
}
}
});
}
});
问题是媒体播放器在歌曲 2 之后停止。但我想让 song3 开始。我可以增加全局变量,好的。但是当第二首歌结束时,onCompletionListener 似乎不起作用。
我想我应该初始化 MediaPlayer mp 也有一个 onCompletionListener 吗?不确定最好的方法是什么。
或者我应该做类似的事情:
new class MediaPlayer implements OnCompletionListener(){
@Override
song++;
//code to start the mediaplayer
}
谢谢你让我朝着正确的方向前进。当我不断启动新的媒体播放器时,我也有点担心效率......
基本上,我想做的是连续播放song1.mid,song2.mid,...,但文件是在程序期间生成的。
编辑 感谢@Gan 的出色帮助。我知道有以下工作代码:
// set on completion listener music file
mediaPlayer
.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
String filePath2 = null;
File file = null;
FileInputStream inputStream = null;
//set the filePath
try {
filePath2 = getCacheDir() + "/optimuse" + song + ".mid";
file = new File(filePath2);
if (file.exists()) {
inputStream = new FileInputStream(file);
if (inputStream.getFD().valid()) {
System.out.println("Valid!");
}
}
} catch (Exception e1) {
e1.printStackTrace();
System.exit(-1);
}
//set Mediaplayer's datasource
if (file.exists()) {
try {
mp.stop();
mp.reset();
mp.setDataSource(inputStream.getFD());
inputStream.close();
} catch (Exception e1) {
e1.printStackTrace();
System.exit(-1);
}
try {
mp.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
//if the player is not running
if (!mp.isPlaying()) {
//start the player
mp.start();
Toast.makeText(MainActivity.this,
"mp.start()", Toast.LENGTH_LONG)
.show();
}
}
});
}
});