这是使用MediaPlayer的正确方法吗?
public class MainActivity extends AppCompatActivity{
MediaPlayer sound1, sound2, sound3, sound4;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Sound MediaPlayers
sound1= MediaPlayer.create(this, R.raw.sound1);
sound2= MediaPlayer.create(this, R.raw.sound2);
sound3= MediaPlayer.create(this, R.raw.sound3);
sound4= MediaPlayer.create(this, R.raw.sound4);
}
//sound onClick's
public void sound1(View view){
sound1.start();
}
public void sound2(View view){
sound2.start();
}
public void sound3(View view){
sound3.start();
}
public void sound4(View view){
sound4.start();
}
}
我必须清理MediaPlayer,但我不知道如何做到这一点。
我知道我必须使用sound1.release()
,但如果我写的话,它不起作用:
public void sound1(View view){
sound1.start();
sound1.release();
}
请举个例子。
答案 0 :(得分:2)
这应该为你工作。
public class MainActivity extends AppCompatActivity{
MediaPlayer mediaPlayer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
//sound onClick's
public void sound1(View view){
cleanUpMediaPlayer();
mediaPlayer = MediaPlayer.create(this, R.raw.sound1);
mediaPlayer.start();
}
public void sound2(View view){
cleanUpMediaPlayer();
mediaPlayer = MediaPlayer.create(this, R.raw.sound2);
mediaPlayer.start();
}
public void sound3(View view){
cleanUpMediaPlayer();
mediaPlayer = MediaPlayer.create(this, R.raw.sound3);
mediaPlayer.start();
}
public void sound4(View view){
cleanUpMediaPlayer();
mediaPlayer = MediaPlayer.create(this, R.raw.sound4);
mediaPlayer.start();
}
public void cleanUpMediaPlayer(){
if(mediaPlayer != null) {
if(mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
mediaPlayer.release();
}
}
}