Search code examples
javaandroidandroid-studioandroid-mediaplayermedia-player

stopping the music and playing it again


I tried to make a small music file reader project , I used the code below sow i can play the music and pause it but once I stop it and click on a button to play it from the begining the music is not played I used the code below and I don t know how to solve that problem :

 final MediaPlayer mp=new MediaPlayer();
        mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
 try {
            mp.setDataSource(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) +String.valueOf("/myfile.mp3"));
        } catch (IOException e) {
            e.printStackTrace();
        }

        btn1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!mp.isPlaying()){
                try{
                    mp.prepare();

                }catch(Exception e){e.printStackTrace();}
                    mp.start();
                    btn1.setText("pause");

                }else{
                    mp.pause();
                    btn1.setText("play");

                }
            }
        });



        btn2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                mp.stop();
                mp.reset();
                btn2.setVisibility(btn2.INVISIBLE);
                btn1.setText("play");

            }
        });

}

Solution

  • Option 1 : you can go back from the beginning with mp.seekTo(0); after calling mp.stop(); also remove the mp.reset(); like this:

    btn2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
    
                mp.stop();
                mp.seekTo(0);
                btn2.setVisibility(btn2.INVISIBLE);
                btn1.setText("play");
    
            }
        });
    

    Option 2 : When calling mp.reset(); you are restoring the object into it's Idle state that's why the music cannot be played. You have to transfer the object into the Initialized state by calling mp.setResource(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) +String.valueOf("/myfile.mp3")); and then mp.prepare(); like this:

    btn2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
    
                mp.stop();
                mp.reset();
                btn2.setResource(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) +String.valueOf("/myfile.mp3"));
                mp.prepare();
                btn1.setText("play");
    
            }
        });
    

    I suggest that you go for Option 1

    I hope this helps. I haven't done any android programming but I know some Java and read the details about the MediaPlayer right here.