main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <Button android:id="@+id/tarzan" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="泰山" android:onClick="onClick" /> <Button android:id="@+id/sneeze" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="哈啾" android:onClick="onClick" /> </LinearLayout>SoundPoolActivity
public class SoundPoolActivity extends Activity {
private static final int SOUND_COUNT = 2;
private int sneezeId;
private int tarzanId;
private SoundPool soundPool;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// 建立 SoundPool
// 第一個參數:SoundPool 不像 MediaPlayer 一個實體管理一個音樂檔案,SoundPool 可以一個實體管理多個檔案
// 第二個參數:串流類型
// 第三個參數:取樣品質,預設用 0
this.soundPool = new SoundPool(SOUND_COUNT, AudioManager.STREAM_MUSIC,
0);
// 載入音樂
// 不像前一個練習直接讀取 SD 卡的檔案,這邊是讀取 resource
this.sneezeId = this.soundPool.load(this, R.raw.sneeze, 1);
this.tarzanId = this.soundPool.load(this, R.raw.tarzan, 1);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.sneeze:
// 第二、三參數分別為左右喇叭的音量,可用 0 到 1
// 第四參數固定用 0
// 第五個參數為播放次數,0 為不重複,-1 為無限重複
// 第六個參數為播放速度,可用 0.5 到 2
this.soundPool.play(this.sneezeId, 1, 1, 0, 0, 1);
break;
case R.id.tarzan:
this.soundPool.play(this.tarzanId, 1, 1, 0, 0, 1);
break;
}
}
}也可以呼叫 pause() 或 stop() 來控制播放。
和 MediaPlayer 一樣,SoundPool 不用以後要在 onPause() 或者 onDestroy() 裡呼叫 release() 釋放資源。
相關文章
沒有留言:
張貼留言