android 迴圈播報電話號碼或數字,並比較MediaPlayer、SoundPool、AudioTrack
android 提供各種音訊播放的方法,目前介紹3鍾
MediaPlayer
這是一個整合度較高的工具類,擁有較全的方法,用於播報號碼來說是大材小用,因為他的提取機制,速度上會受到一定的影響。
會自動解析音訊檔案
播放過程是個併發機制,聲音會疊加一起。但是支援了結束的回撥方法。因此採用遞迴的方法進行語音播報
1先引入音訊檔案,實現結束方法
ZERO=MediaPlayer.create(mcontext,R.raw.zerov); ONE=MediaPlayer.create(mcontext,R.raw.onev); TWO=MediaPlayer.create(mcontext,R.raw.twov); THREE=MediaPlayer.create(mcontext,R.raw.threev); FOUR=MediaPlayer.create(mcontext,R.raw.fourv); FIVE=MediaPlayer.create(mcontext,R.raw.fivev); SIX=MediaPlayer.create(mcontext,R.raw.sixv); SEVEN=MediaPlayer.create(mcontext,R.raw.sevenv); EIGHT=MediaPlayer.create(mcontext,R.raw.eightv); NINE=MediaPlayer.create(mcontext,R.raw.ninev); ZERO.setOnCompletionListener(this); ONE.setOnCompletionListener(this); TWO.setOnCompletionListener(this); THREE.setOnCompletionListener(this); FOUR.setOnCompletionListener(this); FIVE.setOnCompletionListener(this); SIX.setOnCompletionListener(this); SEVEN.setOnCompletionListener(this); EIGHT.setOnCompletionListener(this); NINE.setOnCompletionListener(this);
@Override public void onCompletion(MediaPlayer mp) { if(i!=0) { nextSound(); } }
2實現遞迴方法和傳入
public void playSound(String number){ if(number!=null&&(!number.equals(""))){ chars=number.toCharArray(); i=0; nextSound(); } }
private void nextSound(){ if(chars!=null&&chars.length>0&&i<chars.length){ switch (chars[i]){ case '0': ZERO.start(); break; case '1': ONE.start(); break; case '2': TWO.start(); break; case '3': THREE.start(); break; case '4': FOUR.start(); break; case '5': FIVE.start(); break; case '6': SIX.start(); break; case '7': SEVEN.start(); break; case '8': EIGHT.start(); break; case '9': NINE.start(); break; } if(++i>=chars.length){ i=0; } } }
3傳入電話號碼使用
soundUtil.playSound(number.getText().toString());
11位手機號碼約為3500毫秒唸完。
SoundPool
效能和速度上比MediaPlayer好,但不能監聽結束事件。同樣也是預設併發播放,但能通過設定改為序列播放。
使用上比MediaPlayer簡單。
1初始化方法
musicId = new HashMap(); pool = new SoundPool(1, AudioManager.STREAM_MUSIC, 0); musicId.put('0', pool.load(mcontext, R.raw.zerov, 0)); musicId.put('1', pool.load(mcontext, R.raw.onev, 0)); musicId.put('2', pool.load(mcontext, R.raw.twov, 0)); musicId.put('3', pool.load(mcontext, R.raw.threev, 0)); musicId.put('4', pool.load(mcontext, R.raw.fourv, 0)); musicId.put('5', pool.load(mcontext, R.raw.fivev, 0)); musicId.put('6', pool.load(mcontext, R.raw.sixv, 0)); musicId.put('7', pool.load(mcontext, R.raw.sevenv, 0)); musicId.put('8', pool.load(mcontext, R.raw.eightv, 0)); musicId.put('9', pool.load(mcontext, R.raw.ninev, 0));
2.實現方法
public void playPool(String number){ if(number!=null&&(!number.equals(""))){ chars=number.toCharArray(); for (int j = 0; j < chars.length; j++) { System.out.println("chars[j]="+chars[j]+'='+musicId.get(chars[j])); pool.play(musicId.get(chars[j]),1,1,0,0,1); } } }
3使用
soundUtil.playPool(number.getText().toString());
資源載入速度加快,2500毫秒左右唸完
AudioTrack
直接將byte流傳入播放
約為1500毫秒