Android SoundPool播放提示音

一、SoundPool相對於MediaPlayer的優點
1.SoundPool適合 短且對反應速度比較高 的情況(遊戲音效或按鍵聲等),文件大小一般控制在幾十K到幾百K,最好不超過1M,
2.SoundPool 可以與MediaPlayer同時播放,SoundPool也可以同時播放多個聲音;
3.SoundPool 最終編解碼實現與MediaPlayer相同;
4.MediaPlayer只能同時播放一個聲音,加載文件有一定的時間,適合文件比較大,響應時間要是那種不是非常高的場景
二、SoundPool

    SoundPool soundPool;  
    //實例化SoundPool

    //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());
        soundPool = builder.build();
    } else {
/**
 * 第一個參數:int maxStreams:SoundPool對象的最大併發流數
 * 第二個參數:int streamType:AudioManager中描述的音頻流類型
 *第三個參數:int srcQuality:採樣率轉換器的質量。 目前沒有效果。 使用0作爲默認值。
 */
        soundPool = new SoundPool(1, AudioManager.STREAM_MUSIC, 0);
    }
   
   //可以通過四種途徑來記載一個音頻資源:
   //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 = soundPool.load(context, R.raw.sound, 1);
    //異步需要等待加載完成,音頻才能播放成功
    soundPool.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);
            }
        }
    });
}
.mp3文件放在res/raw文件夾下 ,打包成apk時不會被編譯                                                            .
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章