Search code examples
androidandroid-studioandroid-mediaplayer

Mediaplayer stops working after clicking 14 times


I'm building app which make tic sound on clicking the button. But the sound stops after clicking 14 time. The code is here:

dTextVeiw.setOnClickListener(new View.onClickListener() {
  @Override
  public void onClick(View view){

    MediaPlayer mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.tic_sound);
    mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
    mediaPlayer.start();
  }
});

Solution

  • No need to initialise it every time you click the button.

    private MediaPlayer _mediaPlayer;
    
    @Override
    protected void onResume()
    {
        super.onResume();
        _mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.tic_sound);
        _mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
    }
    
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState)
    {
        //...
    
        dTextVeiw.setOnClickListener(new View.onClickListener() {
            @Override
            public void onClick(View view) {
                _mediaPlayer.start();
            } 
        });
    }