Click here to Skip to main content
15,886,137 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm trying to implement a series of music players in Android. When I press the back button I want the music to stop when the application returns to the the previous screen. I tried lots of solutions and searched online but the app is crashing if I put in lines such as 'stop' and 'release'. Maybe I'm not doing them correctly? Thanks for any help forthcoming... Here is my code...

C#
public class MusicPlayerA extends Activity {

    private MediaPlayer mediaPlayer;
    public TextView songName, duration;
    private double timeElapsed = 0, finalTime = 0;
    private int forwardTime = 2500, backwardTime = 2500;
    private Handler durationHandler = new Handler();
    private SeekBar seekbar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //set the layout of the Activity
        setContentView(R.layout.musicplayerview);
        //initialize views
        initializeViews();
    }

    public void initializeViews(){
        songName = (TextView) findViewById(R.id.songName);
        mediaPlayer = MediaPlayer.create(this, R.raw.druidsad);
        finalTime = mediaPlayer.getDuration();
        duration = (TextView) findViewById(R.id.songDuration);
        seekbar = (SeekBar) findViewById(R.id.seekBar);
        songName.setText("Druids Ad");  
        seekbar.setMax((int) finalTime);
        seekbar.setClickable(true);
    }

    // play mp3 song
    public void play(View view) {
        mediaPlayer.start();
        timeElapsed = mediaPlayer.getCurrentPosition();
        seekbar.setProgress((int) timeElapsed);
        durationHandler.postDelayed(updateSeekBarTime, 100);
    }

    //handler to change seekBarTime
    private Runnable updateSeekBarTime = new Runnable() {
        public void run() {
            //get current position
            timeElapsed = mediaPlayer.getCurrentPosition();
            //set seekbar progress
            seekbar.setProgress((int) timeElapsed);
            //set time remaining
            double timeRemaining = finalTime - timeElapsed;
            duration.setText(String.format("%d min, %d sec", TimeUnit.MILLISECONDS.toMinutes((long) timeRemaining), TimeUnit.MILLISECONDS.toSeconds((long) timeRemaining) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes((long) timeRemaining))));

            //repeat yourself that again in 100 miliseconds
            durationHandler.postDelayed(this, 100);
        }
    };

    // pause mp3 song
    public void pause(View view) {
        mediaPlayer.pause();
    }

    // go forward at forwardTime seconds
    public void forward(View view) {
        //check if we can go forward at forwardTime seconds before song endes
        if ((timeElapsed + forwardTime) <= finalTime) {
            timeElapsed = timeElapsed + forwardTime;

            //seek to the exact second of the track
            mediaPlayer.seekTo((int) timeElapsed);
        }
    }

    // go backwards at backwardTime seconds
    public void rewind(View view) {
        //check if we can go back at backwardTime seconds after song starts
        if ((timeElapsed - backwardTime) > 0) {
            timeElapsed = timeElapsed - backwardTime;

            //seek to the exact second of the track
            mediaPlayer.seekTo((int) timeElapsed);
        }
    }


    public void stopMusic(View view) {
        mediaPlayer.stop();
        mediaPlayer.release();
    }



     // handler for back button used on all screens
     public void BackButton2 (View view) {

        //mediaPlayer.pause();
        //mediaPlayer.release();
         //mediaPlayer.stop();
        // mediaPlayer.release();
        stopMusic(view);

        MediaPlayer mMediaPlayer = MediaPlayer.create(this, R.raw.soundbackbutton) ;
        mMediaPlayer.start();

        Vibrator vib = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
        vib.vibrate(200);

        Intent mus = new Intent (this, Music.class);
        startActivity(mus);
     }

    // handler for back button used on all screens
     public void BackButton (View view) {

        // mediaPlayer.pause();
         //mediaPlayer.release();

        // mediaPlayer.stop();
        // mediaPlayer.release();

        MediaPlayer mMediaPlayer = MediaPlayer.create(this, R.raw.soundbackbutton) ;
        mMediaPlayer.start();

        Vibrator vib = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
        vib.vibrate(200);

        Intent mn = new Intent (this, Music.class);
        startActivity(mn);
     }
}
Posted
Updated 27-Aug-15 12:54pm
v2
Comments
Afzaal Ahmad Zeeshan 27-Aug-15 19:14pm    
Don't they provide an API? I am sure the stop function will be on the same page as is the play.
[no name] 27-Aug-15 19:29pm    
Never work on your UI. Multithreading is your friend. Try something like this freehand code...

Thread ethread = new System.Threading.Thread(DoRun);

private void DoRun()
{
this.Text = "Hello"; //Code for Media player action here.
}

private delegate void DoThisDelegate();
private void MyRoutine()
{
if (this.InvokeRequired) {
this.Invoke(new DoThisDelegate(DoRun));
} else {
this.Text = "Hello";
}
}
You can start the thread in any void/routine with ethread.Start(); Method

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900