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同一时间却只能播放一个。