Search code examples
androidmedia-player

Android Media Player plays sound only once


public void playClickSound() {
AssetFileDescriptor afd;
MediaPlayer sound = new MediaPlayer();  
    try {

        sound.setAudioStreamType(AudioManager.STREAM_MUSIC);
        afd = getAssets().openFd("click.mp3");

sound.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());
        sound.prepare();
        sound.start();

    } catch (IllegalStateException e) {

    } catch (IOException e) {
        e.printStackTrace();
    }

}

This is my code for playing sound. I call this method on a few buttons in mu GUI. It works fine the first time i press the button, but second time i get IllegalStateException. What should I do to make this work?


Solution

  • You need to manage the life-cycle of the Media Player. Following the below flow, should work out:

    RefreshPlayer()
    {
    if (mediaPlayer != null) {
                 {
                    mediaPlayer.stop();
                    mediaPlayer.reset();    
                }
            }
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            try {
                mediaPlayer.setDataSource(getSherlockActivity(),
                        Uri.fromFile(new File(VidPath)));
                mediaPlayer.setLooping(true);
                mediaPlayer.prepare();
                mediaPlayer.start();
    
            } catch (IllegalArgumentException e) 
            {
                e.printStackTrace();
    
            } catch (IllegalStateException e) 
            {
                e.printStackTrace();
    
            } catch (IOException e) 
            {
                e.printStackTrace();
            }
        }