播放音频功能的工具类
/**
* 播放声音工具类
* creator: ZZF
* careate date: 2018/5/25 10:36.
*/
public class SoundUtils {
private SoundPool pool;
private List<Object> listPool = new ArrayList<Object>();
private boolean isOpen;//是否播放声音
public void initPool(Context context) {
setOpen(true);
pool = new SoundPool(10, AudioManager.STREAM_SYSTEM, 5);
//这里添加自己的需要的音频文件
listPool.add(pool.load(context, R.raw.wifi_connected, 0));//wifi已连接 1
listPool.add(pool.load(context, R.raw.wiifi_disconected, 0));//wifi已断开 2
listPool.add(pool.load(context, R.raw.beep, 0));//蜂鸣器 2
}
private static SoundUtils instance = null;
private SoundUtils(){
}
public static SoundUtils getInstance() {
synchronized (SoundUtils.class) {
if (instance == null) {
instance = new SoundUtils();
}
}
return instance;
}
public boolean isOpen() {
return isOpen;
}
public void setOpen(boolean open) {
isOpen = open;
}
/**
* list 坐标位置
* @param flag
*/
public void playVoice(int flag) {
boolean b = isOpen();
if(b){
// 消费成功 提示声音
if (null != pool) {
int index = (Integer) listPool.get(flag);
pool.play(index, 1, 1, 0, 0, 1);
}
}else if(flag == 0 && !b){
flag = (listPool.size()-1);
if (null != pool) {
int index = (Integer) listPool.get(flag);
pool.play(index, 1, 1, 0, 0, 1);
}
}else{
System.out.println("===========语音提示关闭");
}
}
}
使用步骤:
1初始化
在Acitvity或fragment中的onCreate方法
SoundUtils.getInstance().initPool(this);
2 调用
SoundUtils.getInstance().playVoice(1);
文字转语音的工具
生成的音频文件,放到android项目中的res/raw目录下