我正在构建可在单击按钮时发出提示音的应用程序。但是单击14次后声音停止。代码在这里:
javax.annotation.processing.Generated
答案 0 :(得分:1)
无需在每次单击按钮时进行初始化。
private MediaPlayer _mediaPlayer;
@Override
protected void onResume()
{
super.onResume();
_mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.tic_sound);
_mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
}
@Override
protected void onCreate(@Nullable Bundle savedInstanceState)
{
//...
dTextVeiw.setOnClickListener(new View.onClickListener() {
@Override
public void onClick(View view) {
_mediaPlayer.start();
}
});
}
答案 1 :(得分:0)
对于简短的声音,我建议使用SoundPool
Class SoundPlayer(){
private final static float leftVol = 1.0f;
private final static float rightVol = 1.0f;
private final static float rate = 1.0f;
private final static int loop = 0;
private int priority = 1;
private int audioId = = -1;
AudioAttributes attributes = new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_GAME)
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.build();
SoundPool soundPool= new SoundPool.Builder()
.setMaxStreams(2)
.setAudioAttributes(attributes)
.build();
public void loadSounds(Context context){
audioId = soundPool.load(context, R.raw.tic_sound, priority);
}
public void playAudio() {
soundPool.play(audioId, leftVol, rightVol, priority, loop, rate) ;
}
}
并像这样使用它
private SoundPlayer soundPlayer;
....
....
onCreate ...{
soundPlayer = SoundPlayer();
soundPLayer.loadSounds(this);
dTextVeiw.setOnClickListener(new View.onClickListener() {
@Override
public void onClick(View view){
soundPLayer.playAudio();
}