Android中音頻和視頻的播放我們最先想到的就是MediaPlayer類了,該類提供了播放、暫停、停止、和重復播放等方法。該類位于android.media包下,詳見API文檔。其實除了這個類還有一個音樂播放類那就是SoundPool,這兩個類各有不同分析一下便于大家理解
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);
1.?SoundPool最大只能申請1M的內存空間,這就意味著我們只能用一些很短的聲音片段,而不是用它來播放歌 曲或者做游戲背景音樂。
?? 2.?SoundPool提供了pause和stop方法,但這些方法建議最好不要輕易使用,因為有些時候它們可能會使你的程序莫名其妙的終止。Android開發網建議使用這兩個方法的時候盡可能多做測試工作,還有些朋友反映它們不會立即中止播放聲音,而是把緩沖區里的數據播放完才會停下來,也許會多播放一秒鐘。
?? 3.?SoundPool的效率問題。其實SoundPool的效率在這些播放類中算是很好的了,這可能會影響用戶體驗。也許這不能管SoundPool本身,因為到了性能比較好的Droid中這個延遲就可以讓人接受了。
注意soundPool播放的音源文件必須是ogg格式,否則可能會出現莫名其妙的問題