Android 音訊播放之一,android音頻播放

來源:互聯網
上載者:User

Android 音訊播放之一,android音頻播放
SoundPool簡介


Android 中除了 MediaPlayer 播放音頻之外還提供了 SoundPool 來播放音效, SoundPool 使用音效池的概念來管理多個短促的音效,例如它可以開始就載入 20 個音效,以後在程式中按音效的 ID 進行播放。
一、SoundPool的特點


SoundPool 主要用於播放一些較短的聲音片段,與 MediaPlayer 相比, SoundPool 的優勢在於 CPU 資源佔用量低和反應延遲小。另外, SoundPool 還支援自行設定聲音的品質、音量、 播放比率等參數。


SoundPool 提供了一個構造器, 該構造器可以指定它總共支援多少個聲音(也就是池的大小)、聲音的品質等。構造器如下 :


SoundPool(int maxStreams, int streamType, int srcQuality) :第一個參數指定支援多少個聲音;第二個參數指定聲音類型:第三個參數指定聲音品質。


二、SoundPool的初始化
一旦得到了 SoundPool 對象之後,接下來就可調用 SoundPool 的多個重載的 load 方法來載入聲音了 。


SoundPool 提供了如下 4 個 load 方法:


int load(Context context, int resld, int priority) :從 resld 所對應的資源載入聲音。


int load(FileDescriptor fd, long offset, long length, int priority ) :載入 fd 所對應的檔案的 offset 開始、長度為 length 的聲音。


int load(AssetFileDescriptor afd, int priority) :從 afd 所對應的檔案中載入聲音。


int load(String path, int priority ) :從 path 對應的檔案去載入聲音。


上面 4 個方法中都有一個 priority 參數,該參數目前還沒有任何作用, Android 建議將該 參數設為 1 ,保持和未來的相容性。


上面 4 個方法載入聲音之後,都會返回該聲音的的 ID ,以後程式就可以通過該聲音的 ID 來播放指定聲音。




三、SoundPool播放指定聲音的方法:


int play(int soundID, float leftVolume, float rightVolume, int priority, int loop, float rate) :該方法的第一個參數指定播放哪個聲音; leftVolume 、 rightVolume 指定左、右的音量: priority 指定播放聲音的優先順序,數值越大,優先順序越高; loop 指定是否迴圈, 0 為不迴圈, -1 為迴圈; rate 指定播放的比率,數值可從 0.5 到 2 , 1 為正常比率。


為了更好地管理 SoundPool 所載入的每個聲音的 1D ,程式一般會使用一個 HashMap<Integer , Integer> 對象來管理聲音。


歸納起來,使用 SoundPool 播放聲音的步驟如下:


1、調用 SoundPool 的構造器建立 SoundPool 的對象。


2、調用 SoundPool 對象的 load() 方法從指定資源、檔案中載入聲音。最好使用 HashMap< Integer, Integer> 來管理所載入的聲音。


3、調用 SoundPool 的 play 方法播放聲音。


下面的程式示範了如何使用 SoundPool 來播放音效。


程式碼如下:

//聲明變數     SoundPool mSoundPool;     //播放動作聲音id         int mPlaySound;         //停止動作播放聲音id         int mPauseSound;         //執行個體化SoundPool     mSoundPool = new SoundPool(5, AudioManager.STREAM_SYSTEM, 5);     //初始化播放動作音頻         mPlaySound = mSoundPool.load("/system/media/audio/ui/SoundRecorderPlay.ogg", 1);         //初始化停止播放動作音頻         mPauseSound = mSoundPool.load("/system/media/audio/ui/SoundRecorderPause.ogg", 1);                  //播放 播放動作音頻         mSoundPool.play(mPlaySound, 1.0f, 1.0f, 0, 0, 1);         //播放 停止播放動作音頻         mSoundPool.play(mPauseSound, 1.0f, 1.0f, 0, 0, 1);



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.