我在NFC上完成了一个Android项目,我希望在收到NFC日期成功后添加警告音,我该怎么办?
答案 0 :(得分:1)
使用SoundPool类。将您的音频文件放在/ res / raw /中并首先加载它们(例如在OnCreate方法中),然后请求播放选定的音频文件。这是代码示例:
private SoundPool soundPool;
private boolean tiltSoundsLoaded = false;
private int tiltSoundID;
private int tiltFailureSoundID;
public void initTiltSounds(Context context) {
soundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);
soundPool.setOnLoadCompleteListener(new OnLoadCompleteListener() {
@Override
public void onLoadComplete(SoundPool soundPool, int sampleId,
int status) {
tiltSoundsLoaded = true;
}
});
tiltSoundID = soundPool.load(context, R.raw.swosh_sound_effect, 1);
tiltFailureSoundID = soundPool.load(context, R.raw.fail_metallic, 1);
}
public void playTiltSound(AudioManager audioManager, boolean success) {
try{
int soundToPlay;
if(success)
soundToPlay = tiltSoundID;
else
soundToPlay = tiltFailureSoundID;
float actualVolume = (float) audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
if (tiltSoundsLoaded)
soundPool.play(soundToPlay, actualVolume, actualVolume, 1, 0, 1f);
else
Log.e(LOG_TAG, "Tilt Sound not loaded");
}catch(Exception e){
Log.e(LOG_TAG, "Could not play tilt sound");
}
}