Media Player start stop start

后端 未结 9 2105
死守一世寂寞
死守一世寂寞 2020-12-10 13:09

I am making a new android sound application. I made a clickable button to play sound when I click on it. But I also want it to stop playing sound when I click for the second

9条回答
  •  萌比男神i
    2020-12-10 13:36

    In my experience when I need to play multiple times and I may need to stop one play to start another play, (like in the case of multiple buttons), I just create another player, making sure that I release the resources for the previous one. To stop just use

    mediaPlayer.stop(); 
    

    But for play use something like this (adapt the logging to your specific needs) to create/recreate your player:

    private boolean createMediaPlayer()
    {
        if (mediaPlayer!=null)
        {
            if(mediaPlayer.isPlaying())
            {
                mediaPlayer.stop();
                mediaPlayer.reset();
                mediaPlayer.release();
                mediaPlayer=null;
            }
    
        }
        mediaPlayer = new MediaPlayer();
        mediaPlayer.setVolume(1f, 1f);
        try
        {
            mediaPlayer.setAudioStreamType(Interop.PRIMARY_STREAM);
            mediaPlayer.setDataSource(m_soundFile);
            mediaPlayer.prepare();
            return true;
            // Interop.logDebug(TAG + "-loadAudio: SUCCESS" + m_soundFile);
        } catch (Exception e)
        {
            Interop.logError(TAG + "-LoadAudio for Clic Sound: audioPlayer prepare failed for current file: " + m_soundFile);
            Interop.logError(TAG + "-Exception: " , e);
            return false;
        }
    }
    

    and than use

    if (createMediaPlayer())
        mediaPlayer.start();
    

    this will ensure proper release of the resources used by the media player.

提交回复
热议问题