安卓權威編程-筆記(19章 使用SoundPool播放音頻)

來源:互聯網
上載者:User

標籤:pat   legacy   streams   path   span   integer   構造   attribute   play   

針對BeatBox應用,可以使用SoundPool這個特別定製的工具 + 生產力。

SoundPool能載入一批聲音資源到記憶體中,並支援同時播放多個音頻檔案。因此所以,就算使用者興奮起來,狂按按鈕播放全部音頻,也不必擔心會損壞應用或者耗光手機電量。

 

1. 建立SoundPool

1 /*2          * Lollipop引入了新的方式建立SoundPool:使用SoundPool.Builder。為了相容api 16最低層級,只能選擇使用SoundPool(int int int)這個老構造方法。3          * 第一個參數指定同時播放多少個音頻,這裡指定了5個。在播放5個音頻時,如果在嘗試播放第6個,SoundPool會停止播放原來的音頻。4          * 第二個參數確定音頻流類型。5          * 最後一個參數指定採樣率轉換品質。 不起作用 ,傳入 0;6          */7         mSoundPool = new SoundPool(MAX_SOUNDS, AudioManager.STREAM_MUSIC, 0);
8 //下為Sound.Builder方法
 mSoundPool = new SoundPool.Builder()            .setMaxStreams(MAX_SOUNDS)            .setAudioAttributes(new AudioAttributes.Builder()                    .setLegacyStreamType(AudioManager.STREAM_MUSIC)                    .build())            .build();

 

2. 載入音頻檔案

相比其他音頻播放方法,SoundPool還有個快速響應的優勢,指令剛一發出,它就會立即開始播放,一點都不拖遝。代價就是在播放錢必須積極式載入音頻。SoundPool載入的音頻檔案都有自己的Integer類型ID。

在Sound類中添加mSoundId執行個體變數,並添加相應的擷取方法和設定方法管理這寫ID。

然後處理音頻載入,在BeatBox中添加以下代碼:

private void load(Sound sound)throws IOException{        AssetFileDescriptor afd = mAssets.openFd(sound.getAssetPath());        //調用load(AssetFileDescriptor, int)方法可以把檔案載入SoundPool待播、        //此方法返回一個int性ID。這就是儲存在mSoundId中的ID。        int soundId = mSoundPool.load(afd,1);        sound.setSoundId(soundId);    }

然後在BeatBox.loadSounds()方法中,調用load(Sound)方法載入全部音頻檔案。

3.播放音頻

在BeatBox中添加一個play(sound)方法。

 1   public void play(Sound sound){ 2         Integer soundId = sound.getSoundId(); 3         //先檢查並確保soundId是不是null值,Sound載入失敗會導致soundId出現null值。 4         if(soundId == null) 5             return; 6         /* 7         * 調用play方法播放音頻。 8         * 這些參數依次是:音頻ID,左音量,右音量,優先順序(無效),是否迴圈以及播放速率。 9         * 我們需要最大音量和長速播放,所以傳入1.0,是否迴圈參數傳入0值,代表不迴圈。 -1代表迴圈。10          */11         mSoundPool.play(soundId,1.0f,1.0f,1,0,1.0f);12     }

最後添加按鈕監聽器方法,實現點擊按鈕播放音頻。

安卓權威編程-筆記(19章 使用SoundPool播放音頻)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.