Chris
Chris

Reputation: 1

Help/Confused with MediaPlayer for Android?

I been trying to program this soundboard for android but I'm stuck and confused on how to stop a sound from playing when I exit the program with the back key and also when clicking on another sound. I've looked all over the place and even on the android developer website an I'm still confused on what to do. If someone could please help me out i'll greatly appreciate it. My MediaPlayer code im going to post but if the actually soundboard code is needed i'll be happy to post that also.

package com.cs.finalfantasysoundboard;

import android.content.Context;
import android.media.MediaPlayer;

public class Music 
{
    public interface OnCompletionListener {

    }

    private static MediaPlayer mp = null;

    /** Stop old song and start new one */
    public static void play (Context context, int resource)
    {
        stop(context);
        mp = MediaPlayer.create(context, resource);
        mp.stop();
        mp.start();
    }

    /** Stop the music */
    public static void stop(Context context)
    {
        mp.reset();
        mp.release();
        mp = null;
    }
}

Upvotes: 0

Views: 618

Answers (1)

Khawar
Khawar

Reputation: 5227

you can implement some flags for sound being played or stopped etc. Here is how you can stop the sound on Back Key:

 @Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
    if (keyCode == KeyEvent.KEYCODE_BACK /*&& event.getRepeatCount() == 0*/) 
    {           
        if(!isStopped)
        {
            stop();
        }
        //System.exit(0); //if you want to exit directly or this.finish(); etc
        return true;
    }

    return super.onKeyDown(keyCode, event);
}

Upvotes: 1

Related Questions