android之使用SoundPool播放音频

SoundPool可以播一些短的反应速度要求高的声音,资源占用少,反应延迟小,还支持自行设置声音品质,音量,播放比率等,在游戏较为常见。


SoundPool简单实现

package com.leigo.app;

import android.app.Activity;
import android.content.Context;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;

/**
 * Created by Administrator on 2014/9/7.
 */
public class TestActivity extends Activity implements SoundPool.OnLoadCompleteListener {

    private SoundPool mSoundPool;
    private int mSoundId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test);

        mSoundPool = new SoundPool(1, AudioManager.STREAM_MUSIC, 0);
        mSoundId = mSoundPool.load(this, R.raw.phonering, 0);
        mSoundPool.setOnLoadCompleteListener(this);
    }

    @Override
    public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
        AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        int streamVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
        soundPool.play(mSoundId, streamVolume, streamVolume, 0, 0, 1.0f);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mSoundPool.release();
        mSoundPool = null;
    }
}




你可能感兴趣的:(android之使用SoundPool播放音频)