如何使此声音仅播放我选择的声音,直到按下另一个ImageButton,这样它们才不会彼此重叠。
public class MainActivity extends AppCompatActivity {
MediaPlayer leaf,water,fire,wind;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
leaf=MediaPlayer.create(MainActivity.this,R.raw.forest);
water=MediaPlayer.create(MainActivity.this,R.raw.sea);
fire=MediaPlayer.create(MainActivity.this,R.raw.fire);
wind=MediaPlayer.create(MainActivity.this,R.raw.wind);
}
public void playleaf(View view ) {
leaf.setLooping(true);
leaf.start();
}
public void playwater(View view ) {
water.setLooping(true);
water.start();
water.start();
}
public void playfire(View view ) {
fire.setLooping(true);
fire.start();
}
public void playwind(View view ) {
wind.setLooping(true);
wind.start();
}
}
答案 0 :(得分:0)
做这样的事情。
MediaPlayer player;
public void playleaf(View view) {
stopMedia();
player = new MediaPlayer();
player.setDataSource(R.raw.leaf);
player.prepareAsync();
player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
player.setLooping(true);
player.start();
}
});
}
public void playwater(View view) {
stopMedia();
player = new MediaPlayer();
player.setDataSource(R.raw.leaf);
player.prepareAsync();
player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
player.setLooping(true);
player.start();
}
});
}
private void stopMedia() {
if (player != null) {
player.release();
player = null;
}
}
public void playfire(View view) {
stopMedia();
player = new MediaPlayer();
player.setDataSource(R.raw.leaf);
player.prepareAsync();
player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
player.setLooping(true);
player.start();
}
});
}
public void playwind(View view) {
stopMedia();
player = new MediaPlayer();
player.setDataSource(R.raw.leaf);
player.prepareAsync();
player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
player.setLooping(true);
player.start();
}
});
}