Android使用SoundPool播放音效實例詳解

使用場景

SoundPool一般用來 播放密集,急促而又短暫的音效,比如特技音效:Duang~,遊戲用得較多,你也可以爲你的 APP添加上這個音效,比如酷狗音樂進去的時候播放"哈嘍,酷狗" 是不是提起了對於SoundPool的興趣了呢
ok,廢話不多說 詳細的參數解釋請看註釋

public class SoundPlayer extends AppCompatActivity  {

    private SoundPool mSoundPool;


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

        initState();
    }

    private void initState() {
        //sdk版本21是SoundPool 的一個分水嶺
        if (Build.VERSION.SDK_INT >= 21) {
            SoundPool.Builder builder = new SoundPool.Builder();
            //傳入最多播放音頻數量,
            builder.setMaxStreams(1);
            //AudioAttributes是一個封裝音頻各種屬性的方法
            AudioAttributes.Builder attrBuilder = new AudioAttributes.Builder();
            //設置音頻流的合適的屬性
            attrBuilder.setLegacyStreamType(AudioManager.STREAM_MUSIC);
            //加載一個AudioAttributes
            builder.setAudioAttributes(attrBuilder.build());
            mSoundPool = builder.build();
        } else {
            /**
             * 第一個參數:int maxStreams:SoundPool對象的最大併發流數
             * 第二個參數:int streamType:AudioManager中描述的音頻流類型
             *第三個參數:int srcQuality:採樣率轉換器的質量。 目前沒有效果。 使用0作爲默認值。
             */
            mSoundPool = new SoundPool(1, AudioManager.STREAM_MUSIC, 0);
        }

        //可以通過四種途徑來記載一個音頻資源:
        //context:上下文
        //resId:資源id
       // priority:沒什麼用的一個參數,建議設置爲1,保持和未來的兼容性
        //path:文件路徑
       // FileDescriptor:貌似是流吧,這個我也不知道
        //:從asset目錄讀取某個資源文件,用法: AssetFileDescriptor descriptor = assetManager.openFd("biaobiao.mp3");

        //1.通過一個AssetFileDescriptor對象
        //int load(AssetFileDescriptor afd, int priority)
        //2.通過一個資源ID
        //int load(Context context, int resId, int priority)
        //3.通過指定的路徑加載
        //int load(String path, int priority)
        //4.通過FileDescriptor加載
        //int load(FileDescriptor fd, long offset, long length, int priority)
        //聲音ID 加載音頻資源,這裏用的是第二種,第三個參數爲priority,聲音的優先級*API中指出,priority參數目前沒有效果,建議設置爲1。
        final int voiceId = mSoundPool.load(this, R.raw.duang, 1);
        //異步需要等待加載完成,音頻才能播放成功
        mSoundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
            @Override
            public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
                if (status == 0) {
                    //第一個參數soundID
                    //第二個參數leftVolume爲左側音量值(範圍= 0.0到1.0)
                    //第三個參數rightVolume爲右的音量值(範圍= 0.0到1.0)
                    //第四個參數priority 爲流的優先級,值越大優先級高,影響當同時播放數量超出了最大支持數時SoundPool對該流的處理
                    //第五個參數loop 爲音頻重複播放次數,0爲值播放一次,-1爲無限循環,其他值爲播放loop+1次
                    //第六個參數 rate爲播放的速率,範圍0.5-2.0(0.5爲一半速率,1.0爲正常速率,2.0爲兩倍速率)
                    soundPool.play(voiceId, 1, 1, 1, 0, 1);
                }
            }
        });
    }
    }





非常簡單的使用

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章