我认为这是将MediaPlayer用于Button或一次性使用的一种不错的方式。我对吗? try块是否必要?我应该在这里抓到什么?我真的很难找到一种坚如磐石的方式播放一次声音。
// Button sound
private void playButtonSound() {
try{
final MediaPlayer startPlayer = MediaPlayer.create(
getApplicationContext(), R.raw.sound);
startPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
startPlayer.release();
}
});
startPlayer.start();
} catch(Throwable t){}
}
答案 0 :(得分:0)
我这样使用它:
public class PlayaudioActivity extends Activity {
private MediaPlayer mp;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
stopPlaying();
mp = MediaPlayer.create(PlayaudioActivity.this, R.raw.tosse);
mp.start();
}
});
}
private void stopPlaying() {
if (mp != null) {
mp.stop();
mp.release();
mp = null;
}
}
}