我有一个字符串,例如" abcde",并希望通过MediaPlayer拼写它的每个字母。假设它在sdcard文件夹下,a.mp3,b.mp3等我使用:
String s = "abcde";
int length = s.length(); //5
int i = 1;
char current_char = 'a';
mp = new MediaPlayer();
String filePath = "/sdcard/" + current_char + ".mp3";
mp.setDataSource(filePath);
mp.prepare();
mp.start(); //a is played
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
if (i < length) {
current_char = s.charAt(i);
i++;
mp.release();
mp = new MediaPlayer();
filePath = "/sdcard/" + current_char + ".mp3";
mp.setDataSource(filePath);
mp.prepare();
mp.start();
mp.setOnCompletionListener(this);
}
}
});
然而,这只会导致字母&#34; a&#34;仅播放。无法找到错误的内容,我怎么能这样做才能播放所有的字母?非常感谢
答案 0 :(得分:0)
您在调用MediaPlayer.start()后设置OnCompletionListener。
您可能错过了onCompletion事件。
尝试在对象实例之后设置侦听器,如下所示:
mp = new MediaPlayer();
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
if (i < length) {
current_char = s.charAt(i);
i++;
mp.release();
mp = new MediaPlayer();
mp.setOnCompletionListener(this);
filePath = "/sdcard/" + current_char + ".mp3";
mp.setDataSource(filePath);
mp.prepare();
mp.start();
}
}
});
mp.setDataSource(filePath);
mp.prepare();
mp.start(); //a is played