下面列出了android.media.SoundPool#play ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private void shake() {
SoundPool soundPool = new SoundPool(1, AudioManager.STREAM_SYSTEM, 5);
int weiChatAudio = soundPool.load(CodeGenerateActivity.this, R.raw.weichat_audio, 1);
Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
//发出提示音
soundPool.play(weiChatAudio, 1, 1, 0, 0, 1);
vibrator.vibrate(300);
generateGroup();
isShaking = true;
try {
Thread.sleep(100);
isShaking = false;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
/**
* To play sound.
*
* @param context
* {@link Context}
*
* @param soundID
* sound id.
*
* @param soundPool
* {@link SoundPool} instance.
*
*/
public void playSound(Context context, int soundID, SoundPool soundPool){
OnAudioFocusChangeListener afChangeListener = new OnAudioFocusChangeListener() {
public void onAudioFocusChange(int focusChange) {
if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK){
// Lower the volume
} else if (focusChange == AudioManager.AUDIOFOCUS_GAIN) {
// Raise it back to normal
}
}
};
AudioManager audioManager = (AudioManager)context.getSystemService(Context.AUDIO_SERVICE);
// Request audio focus for playback
int result = audioManager.requestAudioFocus(afChangeListener,
// Use the music stream.
AudioManager.STREAM_MUSIC,
// Request permanent focus.
AudioManager.AUDIOFOCUS_GAIN);
if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
// Start playback.
soundPool.play(soundID, 10, 10, 1, 0,1f );
}
}
@Override
public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
AudioNode src = mapLoadingAudioNodes.get(sampleId);
if (src.getAudioData() instanceof AndroidAudioData) {
AndroidAudioData audioData = (AndroidAudioData) src.getAudioData();
if (status == 0) // load was successfull
{
int channelIndex;
channelIndex = soundPool.play(audioData.getId(), 1f, 1f, 1, -1, 1f);
src.setChannel(channelIndex);
// Playing started ?
if (src.getChannel() > 0) {
src.setStatus(Status.Playing);
}
} else {
src.setChannel(-1);
}
} else {
throw new IllegalArgumentException("AudioData is not of type AndroidAudioData for AudioNode " + src.toString());
}
}
private void doAlarm() {
if (mCurrMInfo.isVibrate()){
mVibrator.vibrate(1000);
}
if (mCurrMInfo.isRing()){
SoundPool soundPool = new SoundPool(2, AudioManager.STREAM_SYSTEM, 5);
soundPool.load(this, R.raw.ticket_alarm, 1);
soundPool.play(1, 1, 1, 0, 0, 1);
}
}
public void doAudioAlert(Context context) {
// Use a throttler to keep this from interrupting itself too much.
if (SystemClock.elapsedRealtime() - lastAudioMs < THROTTLE_LIMIT_MS) {
return;
}
SoundPool soundPool = getSoundPool(context);
if (soundId != -1) {
lastAudioMs = SystemClock.elapsedRealtime();
soundPool.play(soundId, .8f, .8f, 0, 0, 1.0f);
}
}
public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
soundPool.play(sampleId, 0.99f, 0.99f, 1, 0, 1);
}