1. 程式人生 > >android之使用SoundPool播放音訊

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;
    }
}