標籤:
android開發播放音效檔
一、 MediaPlayer 播放音訊實現步驟:
1. 調用MediaPlayer.create(context, R.raw.himi);
利用MediaPlayer類調用create方法並且傳入通過id索引的資源音頻檔案,得到執行個體;
2. 得到的執行個體就可以調用 MediaPlayer.star();
此類適合播放較大檔案,此類檔案應該儲存在SD卡上,而不是在資源檔裡,還有此類每次只能播放一個音頻檔案。
播放不同資源方法如下:
1、從資源檔中播放
MediaPlayer player = new MediaPlayer.create(this,R.raw.test);
player.stare();
2、從檔案系統播放
MediaPlayer player = new MediaPlayer();
String path = "/sdcard/test.mp3";
player.setDataSource(path);
player.prepare();
player.start();
3、從網路播放
(1)通過URI的方式:
String path="http://**************.mp3"; //這裡給一個歌曲的網路地址就行了
Uri uri = Uri.parse(path);
MediaPlayer player = new MediaPlayer.create(this,uri);
player.start();
(2)通過設定資料來源的方式:
MediaPlayer player = new MediaPlayer.create();
String path="http://**************.mp3"; //這裡給一個歌曲的網路地址就行了
player.setDataSource(path);
player.prepare();
player.start();
二、 SoundPlayer 播放音訊實現步驟:
1. new出一個執行個體 ;
new SoundPool(4, AudioManager.STREAM_MUSIC, 100);
第一個參數是允許有多少個聲音流同時播放,第2個參數是聲音類型,第三個參數是聲音的品質;
2.loadId = soundPool.load(context, R.raw.himi_ogg, 1);
3. 使用執行個體調用play方法傳入對應的音頻檔案id即可!
下面講下兩個播放形式的利弊:
使用MediaPlayer來播放音頻檔案存在一些不足:
例如:資源佔用量較高、延遲時間較長、不支援多個音頻同時播放等。
這些缺點決定了MediaPlayer在某些場合的使用方式不會很理想,例如在對時間精準度要求相對較高的遊戲開發中。
最開始我使用的也是普通的MediaPlayer的方式,但這個方法不適合用於遊戲開發,因為遊戲裡面同時播放多個音效是常有的事,用過MediaPlayer的朋友都該知道,它是不支援即時播放多個聲音的,會出現或多或少的延遲,而且這個延遲是無法讓人忍受的,尤其是在快速連續播放聲音(比如連續猛點按鈕)時,會非常明顯,長的時候會出現3~5秒的延遲,【使用MediaPlayer.seekTo() 這個方法來解決此問題】;
相對於使用SoundPool存在的一些問題:
1. SoundPool最大隻能申請1M的記憶體空間,這就意味著我們只能使用一些很短的聲音片段,而不是用它來播放歌曲或者遊戲背景音樂(背景音樂可以考慮使用JetPlayer來播放)。
2. SoundPool提供了pause和stop方法,但這些方法建議最好不要輕易使用,因為有些時候它們可能會使你的程式莫名其妙的終止。還有些朋友反映它們不會立即中止播放聲音,而是把緩衝區裡的資料播放完才會停下來,也許會多播放一秒鐘。
3. 音頻格式建議使用OGG格式。使用WAV格式的音頻檔案存放遊戲音效,經過反覆測試,在音效播放間隔較短的情況下會出現異常關閉的情況(有說法是SoundPool目前只對16bit的WAV檔案有較好的支援)。後來將檔案轉成OGG格式,問題得到瞭解決。
4.在使用SoundPool播放音訊時候,如果在初始化中就調用播放函數進行播放音樂那麼根本沒有聲音,不是因為沒有執行,而是SoundPool需要一準備時間。
具體用法如下:
SoundPool soundPool = new SoundPool(4, AudioManager.STREAM_MUSIC, 100); HashMap<Integer, Integer> soundPoolMap = new HashMap<Integer, Integer>(); soundPoolMap.put(1, soundPool.load(this, R.raw.dingdong1, 1)); soundPoolMap.put(2, soundPool.load(this, R.raw.dingdong2, 2)); public void playSound(int sound, int loop) { AudioManager mgr = (AudioManager)this.getSystemService(Context.AUDIO_SERVICE); float streamVolumeCurrent = mgr.getStreamVolume(AudioManager.STREAM_MUSIC); float streamVolumeMax = mgr.getStreamMaxVolume(AudioManager.STREAM_MUSIC); float volume = streamVolumeCurrent/streamVolumeMax; soundPool.play(soundPoolMap.get(sound), volume, volume, 1, loop, 1f); //參數:1、Map中取值 2、當前音量 3、最大音量 4、優先順序 5、重播次數 6、播放速度 } this.playSound(1, 0);
Android播放聲音文體