Search code examples
androidaudioback

Stop audio playback


I am new to Android programming and i have a problem that i can not solve without your help...Please, give me a hand... ;-)

When i start playing my audio file, i can not stop it. Instead, I am quitting the application.

I play audio file with this code:

public class Word1Audio extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.word1video);



        MediaPlayer mediaPlayer = MediaPlayer.create(this, R.raw.lige);
      mediaPlayer.start();



    }

}

HOWEVER, when i try to stop it when the back button is pressed by this piece of code

@Override
public void onBackPressed() {
// do something on back.
return;
}

my applications closes down and audio continues to play...

Do you have an idea why the application closes down? And how can i just stop the music and go back to the previous page...??

Thank you for your time and help... :-)


Solution

  • you could try

     MediaPlayer mediaPlayer;
    
     @Override
     public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.word1video);
        mediaPlayer = MediaPlayer.create(this, R.raw.lige);
        mediaPlayer.start();
     }
    
     @Override
     public void onBackPressed() {
        if( mediaPlayer.isPlaying() ) {
          mediaPlayer.stop();
        }
        super.onBackPressed();
     }