简体   繁体   中英

I have 5 buttons I want to change mediaPlayer source fonClick of the buttons how to do that?

I am having an issue with mediaPlayer I want to change(file) mediaplayer=mediaplayer.create(r.folder."file") with onClick of botton and change it again if another button is pressed. I am having buttons and i want to assign different sounds to be played on every event

使用 switch 语句并根据按钮的 id 创建具有不同来源的媒体文件

Firstly make the MediaPlayer variable global in the activity, and assign it when the onCreate methord fires in your Activity like this

Private MediaPlayer mediaPlayer ;

@Override
public void onCreate() {
    super.onCreate();
    
    //assign the media player
    mediaPlayer = new MediaPlayer();
}

Assuming you have your 5 buttons assigned as { button1 button2 button3 button4 and button5 } , add onclick listeners to all of them like this

button1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //change the music
        }
});

Now what we want to do is that, everytime you click a button we want to reset the existing MediaPlayer and then assign a new file to it, and then play that file.

So in the onClick event of each listener you need to run the code

mediaPlayer.reset();

try {
      mediaPlayer.setDataSource("/storage/emulated/0....path to yor file");
      mediaPlayer.prepare();
      mediaPlayer.start();
    }
catch (Exception ex){
    //we have an exception
};

The onClick listeners for each button should now look like this

//button1
button1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //change the music
            mediaPlayer.reset();

            try {
                  mediaPlayer.setDataSource("/storage/emulated/0....path to yor file");
                  mediaPlayer.prepare();
                  mediaPlayer.start();
                }
                catch (Exception ex){
                //we have an exception
                };



//button 2
button2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //change the music
            mediaPlayer.reset();

            try {
                  mediaPlayer.setDataSource("/storage/emulated/0....path to yor file");
                  mediaPlayer.prepare();
                  mediaPlayer.start();
                }
                catch (Exception ex){
                //we have an exception
                };

        }
});


        }
});


//Button 3 , 4 and 5

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM