2016-04-04 9 views
0

How to make Random sound when button click?SoundPoolを使用してランダムなサウンドを再生する方法は?

私はプログラミングの世界では新しく、以前はランダムなサウンドを再生するためのリファレンスとして試してみました。 SoundPoolを使用しているのは、MediaPlayerよりも短いクリップを再生する方が良いことを理解しているからです。私には合計4つの音があります。

私のアプリケーションを実行すると、残念ながらそれは停止しているというエラーが表示されます。

何が間違っている可能性がありますか?

これは私のコードです:

import java.util.Random; 

public class actibida extends AppCompatActivity { 
SoundPool soundPool; 
Button button; 

protected void onCreate(Bundle savedInstanceState) { 

    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_actibida); 

    final int[] sound = new int[4]; 
    sound[0] = soundPool.load(actibida.this, R.raw.el, 1); 
    sound[1] = soundPool.load(actibida.this, R.raw.guau, 1); 
    sound[2] = soundPool.load(actibida.this, R.raw.miau, 1); 
    sound[3] = soundPool.load(actibida.this, R.raw.quack, 1); 

    final Random r = new Random(); 

    button = (Button) this.findViewById(R.id.button); 
    button.setOnClickListener(new View.OnClickListener() { 

     public void onClick(View button) { 
      soundPool.play(sound[r.nextInt(4)], 1.0f, 1.0f, 0, 0, 1.0f); 
     } 

    }); 
} 

}

答えて

2

あなたが実際に動作するようにSoundPoolのインスタンスを作成していません。 soundPool.loadを呼び出す前に、the SoundPool constructor(またはBuilder API)を使用して、SoundPoolのいくつかのプロパティを定義するインスタンスを作成する必要があります。

+0

ありがとうございました!それはかなりばかげた過ちだった。問題が解決しました。 – Camilo

+0

喜んで助けてください。この回答を正しいものとして受け入れることを忘れないでください。 –

関連する問題