小試身手前的小知識
1. 使用SoundPool有限制,播放的音檔不可以超過 「1mb」大小,所以要放音樂就不能使用這一個方法,要使用MediaPlay
2. SoundPool很容易莫名其妙的自動終止,在使用pause和stop方法時很常很莫名其妙。
3. SoundPool優點為CPU資源使用率低,反應延遲較少。
4. 用來播放一些短短的音效、急促的效果音很好用。
5. 建議使用ogg檔案為音效檔,請先建立資料夾raw放置音效檔案進去。
若已經略懂略懂SoundPool卻有這個問題: 直接放在onCreate裡,卻放不出音效? why? 請參考這篇文章 [Android] SoundPool 音效 ( onCreate版 )
重點程式行
soundPool = new SoundPool(1, AudioManager.STREAM_MUSIC, 5);
第一個參數 SoundPool 內總共放置的音效數目。
第二個參數 串流類型。
第三個參數 音效品質,預設為1我設5,可以試聽看看有一點點差。
alertId = soundPool.load(this, R.raw.pixiedust, 1);
讀取效果音resource的檔案,檔名記得要小寫並且小於1mb
soundPool.play(alertId, 1.0F, 1.0F, 0, 0, 1.0F);
第一個參數 播放哪個音效檔
第二個參數 左喇叭音量
第三個參數 右喇叭音量
第四個參數 固定用 0
第五個參數 0 為不重複,-1 為無限重複
第六個參數 播放速度,可用 0.5 到 2
小試身手小範例
Java檔
import android.app.Activity;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.Button;
public class SoundTest extends Activity {
private int alertId;
private SoundPool soundPool;
private Button alertButton;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.main);
alertButton = (Button)findViewById(R.id.ButtonAlert);
soundPool = new SoundPool(1, AudioManager.STREAM_MUSIC, 5);
alertId = soundPool.load(this, R.raw.pixiedust, 1);
alertButton.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
soundPool.play(alertId, 1.0F, 1.0F, 0, 0, 1.0F);
}
});
}
}
XML檔
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="請按下 ^_________^"
android:textSize="25sp"
android:layout_margin="15sp"
/>
<Button
android:layout_width="100sp"
android:layout_height="wrap_content"
android:id="@+id/ButtonAlert"
android:text="音效按鈕"
android:layout_margin="15sp"
/>
</LinearLayout>