The correct way to play short sounds Android?

后端 未结 3 2027
离开以前
离开以前 2020-12-02 22:33

I am creating an application that will have multiple images on the screen, these images will be buttons and when tapped will play a short sound. I researched this and could

相关标签:
3条回答
  • 2020-12-02 22:55

    You can use SoundPool. It fits what you want to do perfectly.

    You'll just need a way to store the sound effect IDs corresponding to each image (or button).

    Perhaps extend Button to store associated sound effect ID. And use a common SoundPool to play the sound effect associated to the id when the button is touched.

    You can read more about SoundPool here.

    0 讨论(0)
  • 2020-12-02 22:58
    MediaPlayer mp = MediaPlayer.create(getApplicationContext(), R.raw.sound);
    
    try {
        if (mp.isPlaying()) {
            mp.stop();
            mp.release();
    
            mp = MediaPlayer.create(getApplicationContext(), R.raw.sound);
        }
    
        mp.start();
    } catch (Exception e) {
        e.printStackTrace();
    }
    
    0 讨论(0)
  • 2020-12-02 23:19

    @Rikonator is on the right track there with Soundpool. It's much more suited to the kind of functionality you are after.

    If you decide to go with the mediaplayer anyway, though, don't forget the prepareAsync () method to prevent it from hanging the UI thread. You can read more about playing media here.

    0 讨论(0)
提交回复
热议问题