android開發:播放音訊功能的工具類
阿新 • • 發佈:2019-02-16
播放音訊功能的工具類
/**
* 播放聲音工具類
* 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目錄下