簡體   English   中英

如何使用SoundPool播放隨機聲音?

[英]How to play a random sound using SoundPool?

單擊按鈕時如何發出隨機聲音?

我對編程世界還很陌生,我之前已經檢查了上面的鏈接以嘗試將其用作播放隨機聲音的參考。 我正在使用SoundPool,因為我知道播放短片比MediaPlayer更好。 我總共有四個聲音。

當我運行我的應用程序時,我收到一條錯誤消息,不幸的是它已停止。

關於什么可能是錯誤的任何想法?

這是我的代碼:

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);
        }

    });
}

}

您實際上尚未創建要使用的SoundPool實例。 在調用soundPool.load之前,必須使用SoundPool構造函數 (或Builder API)創建一個實例,該實例定義SoundPool的某些屬性。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM