目次へ
|
■■■■SoundPoolとMediaPlayer■■■■
SoundPool、MediaPlayer のどちらも音を鳴らすときに使います。BGMのような長い音楽を鳴らすにはMediaPlayer、短い効果音などを鳴らすときには、SoundPoolが向いています。
SoundPoolの場合には、メモリにロードされた状態にしておいて、音を鳴らすため、遅延が少ないのが特徴です。
■■■■SoundPoolを使って効果音を鳴らす方法■■■■
使いたい効果音データはリソースとして、プロジェクトのresフォルダ内にrawという名前のフォルダを作成し、その中に保存をします。SoundPoolのインスタンスを作成するには、SoundPool.Builderクラスのbuildメソッドを使います。
音を再生するにはplayメソッドを使います。
playメソッドの引数は次のようになっています。
int play (int soundID, float leftVolume, float rightVolume, int priority, int loop, float rate) soundID サウンドID。loadメソッドが返した値 leftVolume 左のボリューム。範囲は0.0 ~ 1.0 rightVolume 右のボリューム。範囲は0.0 ~ 1.0 priority 優先度。0が優先度が最も低い loop ループモード。0:ループしない。-1:ループする rate 再生速度。1:ノーマル。範囲は 0.5 ~ 2.0 |
下の例はbutton1を押すと、nyao.wav、button2を押すとgao.wavを再生します
playメソッドの引数を変更することにより、button1の方が小さい音。button2の方が大きい音となり、 また、button2の再生スピードの方が速く(高く)なります。
リソースは res/rawにnyao.wav、gao.wavを入れています。
public class MainActivity extends Activity {
SoundPool soundPool;
int sound1;
int sound2;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//--------------------- SoundPoolのインスタンス作成
SoundPool.Builder builder = new SoundPool.Builder();
soundPool = builder.build();
//--------------------- 効果音をロードしておく。
//------------引数はContext、リソースID、優先度
sound1 = soundPool.load(this, R.raw.gao, 1);
sound2 = soundPool.load(this, R.raw.nyao, 1);
//---------------- button1を押すと効果音(nyao.wav)が鳴る。
Button button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
soundPool.play (sound1,0.5f,0.5f,0,0,1);
}
});
//------------------button2を押すと効果音(gao.wav)が鳴る。
Button button2 = (Button) findViewById(R.id.button2);
button2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
soundPool.play (sound2,1.0f,1.0f,0,0,2);
}
});
}
}
|
にほんブログ村