2016-04-11 9 views
0

次のコードはランダムなサウンドを再生します。私はもう何も再生するためにボタンを必要としないので解放しようとしていますが、アプリケーションを実行すると、ボタンはサウンドをまったく再生しません。SoundPoolオブジェクトを正しく解放するにはどうすればいいですか?

public class actibida extends AppCompatActivity { 
SoundPool soundPool; 
Button button; 
boolean loaded = false; 

protected void onCreate(Bundle savedInstanceState) { 

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

    soundPool = new SoundPool(1, AudioManager.STREAM_MUSIC, 0); 
    soundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() { 
     @Override 
     public void onLoadComplete(SoundPool soundPool, int sampleId, int status) { 
      loaded = true; 
     } 
    }); 

    //I have a total of four sounds 
    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) { 

      final Random r = new Random(); 
      int Low = 0; 
      int High = 3; 
      int rndm = r.nextInt(High - Low) + Low; 
      soundPool.play(sound[r.nextInt(4)], 1.0f, 1.0f, 0, 0, 1.0f); 


     } 

    }); 
    soundPool.release(); 
     } 
} 

誰かが)(正しく.release呼び出す方法で私を教育してくださいことはできますか?

P.S.私がアプリでいくつかの他のサウンドを演奏しようとしたら、別のSoundPoolクラスを使うべきですか?それとも私はそれをリリースして再度ロードするべきですか?事は私が最初に解放することさえできないので、私は言うことができません。

答えて

0

サウンドが再生される前に、SoundPoolを解放しています。実際には、再生が始まる瞬間にそれをリリースしています。 play()メソッドはサウンドが終了するのを待たず、再生は非同期です。また、再生がいつ終了するかを知る方法はありません。

今後同じサウンドプールからプレイする場合は、SoundPoolをシングルトンのようなものにしたり、再利用できる場所に保存したりすることができます。

+0

誰かが残りのコードをチェックできるように、私はその投稿を編集しました。私はsoundPool.release()を配置しようとしました。しかし、それはまだ動作しません。私はそれを置くべきだったか? – Camilo

+0

アクティビティの終了後に使用しない場合は、onDestroy()で解放してください。 –

関連する問題