• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Apps Multiple button with different music in each button issue

Yen Yu

Lurker
Hi Guys,

I'm have manage to create some buttons tagging to afew different songs, but here's the issue, when I click the first button, it plays the music, immediately clicking the second button, the second music is played overlapping the first music. In this case, 2 musics are playing concurrently. How do I go about stopping the first music when the 2nd or subsequent button is clicked?

Need some guidance and appreciate on the above as I did some googling and looked into other games working apk scripts and unable to get hold of this portion.
 
Just call stop() method of the player, than set up new resource and call play() method on each button click

player.stop();
player.setDataSource("file.mp3");
player.play();
 
Hi, Thanks for the assistance. I've tried it out, but it always cause my app to crash and meet fatal error. Below is one of the short program for one of my button.

package com.main.etutor;
import android.media.MediaPlayer;
import android.content.Context;

public class BtnButton15 {
private static MediaPlayer mp = null;
//private static MediaPlayer mpEffect = null;
public static void play(Context context, int resources)
{
mp.stop();
mp = MediaPlayer.create(context, resources);
mp.start();
}





}
 
you are trying to call stop() method of null object, do it like this

Code:
package com.main.etutor;
import android.media.MediaPlayer;
import android.content.Context;

public class BtnButton15 {
private static MediaPlayer mp = null;
//private static MediaPlayer mpEffect = null;
public static void play(Context context, int resources)
{
if(mp != null){
mp.stop();
}
mp = MediaPlayer.create(context, resources);
mp.start();
}
 
Hi Willie,

Thanks for the guidance, but i've modified to the following:
Java:
public class BtnButton15 {

    public static MediaPlayer mp = new MediaPlayer();
    //private static MediaPlayer mpEffect = null;
    public static void play(Context context, int resources)
    {
        mp.stop();
        mp = MediaPlayer.create(context, resources);
        mp.start();
    }
}
This works pretty fine with I reselect the same button, "BtnButton15", but when I start selecting other buttons, it still being the same playing 2 or more songs concurrently. While using your modified codes, it's not working even though it is logically correct. I believe it is the declaration of:
Java:
Public static MediaPlayer mp = new MediaPlayer();
which plays the most critical portion which using back ur same code and it should work well. Is it possible to declare this as a global variable or value outside the public class BtnButton15 which all button will check if this MediaPlay mp is having something before executing the if-else portion?
 
Back
Top Bottom