Android SoundPool 如何连续播报多个语音
首先看一下SoundPool的工具类方法//load 音频资源public static void loadAudioSources(Context context){soundMap.put(1, soundpool.load(context, R.raw.onenew, 1));soundMap.put(2, soundpool.load(context, R.raw.twonew, 1));
·
首先看一下SoundPool的工具类方法
//load 音频资源
public static void loadAudioSources(Context context){
soundMap.put(1, soundpool.load(context, R.raw.onenew, 1));
soundMap.put(2, soundpool.load(context, R.raw.twonew, 1));
soundMap.put(3, soundpool.load(context, R.raw.threenew, 1));
soundMap.put(4, soundpool.load(context, R.raw.fournew, 1));
soundMap.put(5, soundpool.load(context, R.raw.fivenew, 1));
soundMap.put(6, soundpool.load(context, R.raw.sixnew, 1));
soundMap.put(7, soundpool.load(context, R.raw.sevennew, 1));
soundMap.put(8, soundpool.load(context, R.raw.eightnew, 1));
soundMap.put(9, soundpool.load(context, R.raw.ninenew, 1));
soundMap.put(10, soundpool.load(context, R.raw.zeronew, 1));
soundMap.put(11, soundpool.load(context, R.raw.pleasenew, 1));
soundMap.put(12, soundpool.load(context, R.raw.comenew, 1));
soundMap.put(13, soundpool.load(context, R.raw.windownew, 1));
soundMap.put(14, soundpool.load(context, R.raw.a, 1));
}
// play 音频资源
public static void playAudio(int id){
// rate:播放的速率,范围0.5-2.0(0.5为一半速率,1.0为正常速率,2.0为两倍速率)
soundpool.play(soundMap.get(id), 1, 1, 0, 0, (float) 1.1);
}
/**
* 获取语音播放的id
* */
public static int getSoundSpeaker(String str){
switch (str){
case "1":
return 1;
case "2":
return 2;
case "3":
return 3;
case "4":
return 4;
case "5":
return 5;
case "6":
return 6;
case "7":
return 7;
case "8":
return 8;
case "9":
return 9;
case "0":
return 10;
case "A":
return 14;
default:
return 0;
}
}
当我们调用上述的playAudio方法时,就是播放对应的音频文件了。此时我们没有办法控制播放的过程,如果我们连续播放多个音频,就一定要注意播放时间的问题。只有播放完上一个音频,才能继续播放下一个音频,否则声音会重叠。如下代码,使用Thread.sleep等待语音播放。
final Runnable mSpeakRunnableNew = new Runnable() {
@Override
public void run() {
String WindowNum = "A4003";
String NumDataNew = "01";
int id = 0;
try {
// just for speaker
Thread.sleep(200);
SoundPoolUtil.playAudio(11);
Thread.sleep(300);
for (int i=0; i<WindowNum.length(); i++){
String str = String.valueOf(WindowNum.charAt(i));
Thread.sleep(260);
id = SoundPoolUtil.getSoundSpeaker(str);
if (id > 0) {
SoundPoolUtil.playAudio(id);
}
}
Thread.sleep(300);
SoundPoolUtil.playAudio(12);
Thread.sleep(200);
for (int i=0; i<NumDataNew.length(); i++){
String str = String.valueOf(NumDataNew.charAt(i));
Thread.sleep(230);
id = SoundPoolUtil.getSoundSpeaker(str);
if (id > 0) {
SoundPoolUtil.playAudio(id);
}
}
Thread.sleep(300);
SoundPoolUtil.playAudio(13);
} catch (Exception e) {
}
}
};
如果把所有需要播放的资源id放到一起,也可以使用以下方法
/**
* 音频播放线程
*/
private class PlayThread extends Thread {
@Override
public void run() {
Set<Integer> soundIdSet = soundIdMap.keySet();
for (Integer soundId : soundIdSet) {
soundPool.play(soundId, 1, 1, 0, 0, 1);
try {
//获取当前音频的时长
Thread.sleep(soundIdMap.get(soundId));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
更多推荐
所有评论(0)