[英]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.我在使用 mediaPlayer 时遇到问题我想使用 onClick 按钮更改(文件)mediaplayer=mediaplayer.create(r.folder."file") 并在按下另一个按钮时再次更改它。 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首先在活动中使 MediaPlayer 变量成为全局变量,并在您的活动中触发 onCreate 方法时分配它,如下所示
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假设您将 5 个按钮分配为 { button1 button2 button3 button4 和 button5 } ,请像这样向所有按钮添加 onclick 侦听器
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.现在我们要做的是,每次单击按钮时,我们都希望重置现有的 MediaPlayer,然后为其分配一个新文件,然后播放该文件。
So in the onClick event of each listener you need to run the code所以在每个监听器的onClick事件中都需要运行代码
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每个按钮的 onClick 侦听器现在应如下所示
//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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.