gpt4 book ai didi

java - 多个媒体播放器合二为一

转载 作者:行者123 更新时间:2023-11-30 05:05:10 25 4
gpt4 key购买 nike

我正在制作音板应用程序,并且在我的 Java 文件中添加了很多 MediaPlayer 实例,以便在我单击 CardView 时启动。有什么办法可以将它们全部集成到一个媒体播放器中吗?

//Muziekje bingo
final MediaPlayer bingoMediaPlayer = MediaPlayer.create(this, R.raw.bingo);

final CardView bingo = (CardView) this.findViewById(R.id.play_bingo);

bingo.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
bingoMediaPlayer.start();
bingo.setCardBackgroundColor(Color.parseColor("#707980"));
}
});

bingoMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
bingo.setCardBackgroundColor(Color.parseColor("#b3bac0")); // finish current activity
}
});

//muziekje harrypotter
final MediaPlayer harrypotterMediaPlayer = MediaPlayer.create(this, R.raw.harrypotter);

final CardView harrypotter = (CardView) this.findViewById(R.id.play_harrypotter);

harrypotter.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
harrypotterMediaPlayer.start();
harrypotter.setCardBackgroundColor(Color.parseColor("#707980"));
}
});


harrypotterMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
harrypotter.setCardBackgroundColor(Color.parseColor("#b3bac0")); // finish current activity
}
});

//muziekje bibet
final MediaPlayer bibetMediaPlayer = MediaPlayer.create(this, R.raw.bibet);

final CardView bibet = (CardView) this.findViewById(R.id.play_bibet);

bibet.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
bibetMediaPlayer.start();
bibet.setCardBackgroundColor(Color.parseColor("#707980"));
}
});



bibetMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
bibet.setCardBackgroundColor(Color.parseColor("#b3bac0")); // finish current activity
}
});

最佳答案

您可以编写一个函数来播放相关的音乐文件。这将帮助您摆脱样板代码。

public void playSound(int music) {
//mContext will be your context here
MediaPlayer.create(mContext, music).start();
}

你可以像这样在你的代码中使用这个函数

bingo.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
playSound(R.raw.bingo);
bingo.setCardBackgroundColor(Color.parseColor("#707980"));
}
});

harrypotter.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
playSound(R.raw.harrypotter);
harrypotter.setCardBackgroundColor(Color.parseColor("#707980"));
}
});

希望对你有帮助。

关于java - 多个媒体播放器合二为一,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54700222/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com