Android平臺中關於音頻的播放有兩種方式:一種是SoundPool,一種是MediaPlayer。SoundPool適合短促但對反應速度要求較高的情況(如遊戲中的爆炸聲),而MediaPlayer則適合較長但對時間要求不高的情況(如背景音樂)。下面以例子說明:
首先在res中添加raw文件夾,然後添加兩首音樂:
這裏需要注意的是,對於SoundPool音樂,拓展名需改爲“ogg” ,而MediaPlayer音樂則改爲“mid” , 否則可能無法正常播放。
然後在創建的Activity中寫入如下代碼:
package sugite.sample;
import java.util.HashMap;
import android.app.Activity;
import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.SoundPool;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class Sample_Activity extends Activity implements OnClickListener{
Button button1 ; //四個按鈕的引用
Button button2 ;
Button button3 ;
Button button4 ;
TextView textView; //TextView的引用
MediaPlayer mMediaPlayer; //MediaPlayer的引用
SoundPool soundPool;//SoundPool的引用
HashMap<Integer,Integer> soundPoolMap;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initSounds(); //初始化聲音
textView = (TextView)this.findViewById(R.id.textView);
button1 = (Button)this.findViewById(R.id.button1);
button2 = (Button)this.findViewById(R.id.button2);
button3 = (Button)this.findViewById(R.id.button3);
button4 = (Button)this.findViewById(R.id.button4);
button1.setOnClickListener(this);
button2.setOnClickListener(this);
button3.setOnClickListener(this);
button4.setOnClickListener(this);
}
private void initSounds() {//初始化聲音的方法
// TODO Auto-generated method stub
mMediaPlayer = MediaPlayer.create(this, R.raw.backsound);//初始化MediaPlayer
soundPool = new SoundPool(4,AudioManager.STREAM_MUSIC,100);
soundPoolMap = new HashMap<Integer,Integer>();/*使用SoundPool時一般將聲音放進一個
HashMap中,便於聲音的管理與操作。*/
soundPoolMap.put(1, soundPool.load(this, R.raw.dingdong,1));
}
public void palySound(int sound , int loop){ //用SoundPool播放聲音的方法
AudioManager mgr = (AudioManager)this.getSystemService(Context.AUDIO_SERVICE);
//在這個方法中,必須先對聲音設備進行配置,然後調用SoundPool的play方法來播放聲音。
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);//播放聲音
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v == button1){
textView.setText("使用MediaPlayer播放聲音");
if(!mMediaPlayer.isPlaying())
mMediaPlayer.start();
}else if(v == button2){
textView.setText("暫停了MediaPlayer播放的聲音");
if(mMediaPlayer.isPlaying())
mMediaPlayer.pause();
}else if (v== button3){
textView.setText("使用了SoundPool播放聲音");
this.palySound(1, 0);
}else if(v == button4){
textView.setText("暫停了SoundPool播放的聲音");
soundPool.pause(1);
}
}
}
運行以上代碼的結果將是下面這樣:
可以通過按鈕來播放或者暫停音樂。
SoundPool初始化的過程是異步的,也就是說,當對SoundPool初始化時系統會自動啓動一個後臺線程來完成初始化工作。因此並不會影響前臺其他程序的運行,但也帶來一個問題,調用初始化操作後不能立即播放,需要等待一點時間,否則可能會出錯。另外,SoundPool可以同時播放多個音頻文件,但MediaPlayer同一時間卻只能播放一個。