標籤:
MediaPlayer:
此類適合播放較大檔案,此類檔案應該儲存在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();
SoundPool:
此類特點就是低延遲播放,適合播放即時音實現同時播放多個聲音,如遊戲中炸彈的爆炸音等小資源檔,此類音頻比較適合放到資源檔夾 res/raw下和程式一起打成APK檔案。
用法如下:
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音頻播放執行個體