音效播放:
资源文件: res/raw/filename
声音池类:SoundPool sp = new SoundPool(同时最大播放个数,AudioManager.STREAM_MUSIC,0);
将加载里音频文件的SoundPool添加到一个HashMap中,提供给以后的调用
HashMap<Integer,Integer> spMap = new HashMap<Integer, Integer>();
spMap.put(1,sp.load(this, R.raw.filename1,1));
spMap.put(2,sp.load(this, R.raw.filename2,1));
音效播放函数:
public void playSounds(int sound, int number){
//实例化AudioManager对象,控制声音
AudioManager am = (AudioManager)this.getSystemService(this.AUDIO_SERVICE);
//最大音量
float audioMaxVolumn = am.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
//当前音量
float audioCurrentVolumn = am.getStreamVolume(AudioManager.STREAM_MUSIC);
float volumnRatio = audioCurrentVolumn/audioMaxVolumn;
//播放
sp.play(spMap.get(sound), //声音资源
volumnRatio, //左声道
volumnRatio, //右声道
1, //优先级,0最低
number, //循环次数,0是不循环,-1是永远循环
1); //回放速度,0.5-2.0之间。1为正常速度
}
音效暂停:
sp.pause(spMap.get(1));
代码如下:
/**************************** TestSounds.java **************************************/
import java.util.HashMap;
import android.app.Activity;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class TestSounds extends Activity {
private Button bPlay;
private Button bPause;
private SoundPool sp;
private HashMap<Integer,Integer> spMap;
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
bPlay = (Button)findViewById(R.id.button01);
bPause = (Button)findViewById(R.id.button02);
sp = new SoundPool(2,AudioManager.STREAM_MUSIC,0);
spMap = new HashMap<Integer,Integer>();
spMap.put(1, sp.load(this, R.raw.qiang, 1));
bPlay.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
playSounds(1,1);
}
});
bPause.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
sp.pause(spMap.get(1));
}
});
}
public void playSounds(int sound, int number){
AudioManager am = (AudioManager)this.getSystemService(this.AUDIO_SERVICE);
float audioMaxVolumn = am.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
float audioCurrentVolumn = am.getStreamVolume(AudioManager.STREAM_MUSIC);
float volumnRatio = audioCurrentVolumn/audioMaxVolumn;
sp.play(spMap.get(sound), volumnRatio, volumnRatio, 1, number, 1);
}
}
/******************************** main.xml *********************************/
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button
android:id="@+id/button01"
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:text="Play"></Button>
<Button
android:id="@+id/button02"
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:text="Pause"></Button>
</LinearLayout>