標籤:android 多媒體 soundpool
之前學習過了MediaPlayer用於播放手機音樂,但是在手機中很多的提示音並不是使用MediaPlayer來播放的比如簡訊鈴聲,通知鈴聲,android中使用SoundPool來播放小的音頻檔案;
下面一起學習SoundPool的使用
【1】先搭介面設定一個按鈕用於播放開始
【2】得到SoundPool
查看API,得知要得到SoundPool根據版本不同有兩種方式
21版本以前使用
SoundPool pool =new SoundPool(int maxStreams, int streamType, int srcQuality)
21版本之後:使用Builder來產生
【3】調用load方法載入音頻
【4】調用play方法
public final int play (int soundID, float leftVolume, float rightVolume, int priority, int loop, float rate)
參數介紹
Parameters
soundID a soundID returned by the load() function
leftVolume left volume value (range = 0.0 to 1.0)左聲道
rightVolume right volume value (range = 0.0 to 1.0)右聲道
priority stream priority (0 = lowest priority)優先順序
loop loop mode (0 = no loop, -1 = loop forever)迴圈與否
rate playback rate (1.0 = normal playback, range 0.5 to 2.0)播放返回的速度
注意事項
如果你的沒有聲音,那是因為載入音頻需要時間,不要把load和play放在一起
也不要使線程休眠,以免阻礙主線程
下面是源碼
public class MainActivity extends Activity { private Button mButton; private SoundPool pool = null; private int id; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mButton = (Button) findViewById(R.id.button_sound); //必須放在外面因為載入音頻需要時間不然會沒有聲音 id= initSound(); mButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { playSound(); } }); } private void playSound() { //public final int play (int soundID, float leftVolume, float rightVolume, int priority, int loop, float rate)// Parameters// soundID a soundID returned by the load() function// leftVolume left volume value (range = 0.0 to 1.0)左聲道// rightVolume right volume value (range = 0.0 to 1.0)右聲道// priority stream priority (0 = lowest priority)優先順序// loop loop mode (0 = no loop, -1 = loop forever)迴圈與否// rate playback rate (1.0 = normal playback, range 0.5 to 2.0)播放返回的速度 pool.play(id, 1, 1, 0, -1, 1); } public int initSound() { if (Build.VERSION.SDK_INT > 21) { SoundPool.Builder builder = new SoundPool.Builder(); builder.setMaxStreams(2); AudioAttributes.Builder builder1 = new AudioAttributes.Builder(); builder1.setLegacyStreamType(AudioManager.STREAM_MUSIC); builder.setAudioAttributes(builder1.build()); pool = builder.build(); } else { //21版本以前使用SoundPool(int maxStreams, int streamType, int srcQuality) pool = new SoundPool(2, AudioManager.STREAM_MUSIC, 0); } return pool.load(getApplicationContext(), R.raw.outgoing, 1); }}
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。
android多媒體——4步學會SoundPool