SoundPool的優點是可以同時撥好幾個音檔
但卻對音檔的大小有限制
因此只適合撥較短的音檔
以下範例UI會有左右聲道的播放及停止按鈕
MainActivity.java
package com.qn.leftrightsound; import android.media.AudioManager; import android.media.SoundPool; import android.os.Bundle; import android.app.Activity; import android.util.Log; import android.view.View; import android.widget.Button; public class MainActivity extends Activity { private String TAG = "leftrightsound"; private SoundPool soundPool; private Button button_left_play, button_left_pause, button_right_play, button_right_pause; private int music_left, music_right; private int music_left_temp, music_right_temp; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); soundPool = new SoundPool(1, AudioManager.STREAM_MUSIC, 0); music_left = soundPool.load(this, R.raw.left_sound, 1); music_right = soundPool.load(this, R.raw.right_sound, 1); // 音樂檔案放在res/raw底下,預設沒有raw資料夾,要自己建 button_left_play = (Button) findViewById(R.id.button_left_play); button_left_pause = (Button) findViewById(R.id.button_left_pause); button_right_play = (Button) findViewById(R.id.button_right_play); button_right_pause = (Button) findViewById(R.id.button_right_pause); button_left_play.setOnClickListener(ButtonListner); button_left_pause.setOnClickListener(ButtonListner); button_right_play.setOnClickListener(ButtonListner); button_right_pause.setOnClickListener(ButtonListner); } private Button.OnClickListener ButtonListner = new Button.OnClickListener() { @Override public void onClick(View v) { switch (v.getId()) { case R.id.button_left_play: Log.i(TAG, "press left play"); music_left_temp = soundPool.play(music_left, 1, 1, 0, 0, 1); // 由於每次播放的id會不同,為考慮到按下暫停是要暫停剛剛播放的,因此將每次播放的id存起來 // play() // 第一參數為音檔id // 第二.三參數為左右聲道的音量,range = 0.0 to 1.0 // 第四參數為優先權,若不需設定可都設為0,0為最小優先權 // 第五參數為loop,0 = no loop, -1 = loop forever // 第六參數為速度,1.0 = normal playback, range 0.5 to 2.0 break; case R.id.button_left_pause: Log.i(TAG, "press left pause"); soundPool.stop(music_left_temp); break; case R.id.button_right_play: Log.i(TAG, "press right play"); music_right_temp = soundPool.play(music_right, 0, 1, 0, 0, 1); break; case R.id.button_right_pause: Log.i(TAG, "press right pause"); soundPool.stop(music_right_temp); break; } } }; @Override protected void onDestroy() { this.soundPool.release(); super.onPause(); } }
沒有留言:
張貼留言