0

I want to play mp3 file from res/raw folder when user click on button

my code is below:

btn.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View arg0) {
        MediaPlayer mp = MediaPlayer.create(MainActivity.this,
        R.raw.click);
        mp.start();
    }
});

Work well but take some time to play after button click. please, anyone, give me a solution. Thanks

SahdevRajput74
  • 742
  • 6
  • 18

3 Answers3

2

Loading time depends on the buffer size of the MediaPlayer (which is hardcoded in the firmware) and that there is nothing that can be done to change it. Read more here.

iamgopal
  • 554
  • 4
  • 11
1

This is as a result of the buffer size of media player.

Try using SoundPool for a more responsive playback. You can see an implementation of it here.

SoundPool soundPool = new SoundPool(1, AudioManager.STREAM_MUSIC, 100);
HashMap<Integer, Integer> soundPoolMap soundPoolMap = new HashMap<Integer, Integer>();
soundPoolMap.put(soundID, soundPool.load(this, R.raw.click, 1));

Start the sound with soundPool.play(soundId, 1, 1, 1, 0, 0);

HackNode
  • 159
  • 2
  • 10
1

Option 1:

Instead of creating the media player and then calling start() method in the onClick of the button, you can initialize the mediaPlayer in onCreate() of activity.

As for the button click implementation, you need to call mediaPlayer.start() only.

Option 2: You can use SoundPool API provided by Android. This has lower latency compared to MediaPlayer API. SoundPool are recommended mainly for playing short clips.

  • @SahdevRajput74 If any answer is helpful to you and solve your problem then you can mark as correct : https://i.stack.imgur.com/DGNzO.png – Vishva Dave Feb 21 '18 at 06:44