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();
player.stop();
player.reset();//對MediaPlayer重設,重設後可以重新配置資源並調用
player.release();//對MediaPlayer釋放,釋放後不能再調用。
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);