溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Android中如何使用SoundPool播放音頻

發(fā)布時(shí)間:2022-04-11 16:34:55 來源:億速云 閱讀:683 作者:iii 欄目:編程語言

這篇文章主要介紹了Android中如何使用SoundPool播放音頻的相關(guān)知識(shí),內(nèi)容詳細(xì)易懂,操作簡單快捷,具有一定借鑒價(jià)值,相信大家閱讀完這篇Android中如何使用SoundPool播放音頻文章都會(huì)有所收獲,下面我們一起來看看吧。

使用SoundPool播放音效

SoundPool類可用于管理和播放應(yīng)用中的音頻資源,這些音頻資源可以放在存儲(chǔ)文件中也可以包含在程序中,一般來說,SoundPool用來播放比較短的音效,比如游戲中的各種音效

首先創(chuàng)建一個(gè)SoundPool對(duì)象

    private SoundPool sp;

然后

  1. 創(chuàng)建Builder對(duì)象,用 SoundPool.Builder builder

  2. 設(shè)置最大音頻數(shù)量,setMaxStreams()

  3. 預(yù)設(shè)音頻類型,setLegacyStreamType()

  4. 設(shè)置音頻類型,setAudioAttributes()

 if (Build.VERSION.SDK_INT >= 21) {
            SoundPool.Builder builder = new SoundPool.Builder();
            builder.setMaxStreams(2);
            AudioAttributes.Builder attrBuilder = new AudioAttributes.Builder();
            attrBuilder.setLegacyStreamType(AudioManager.STREAM_MUSIC);
            builder.setAudioAttributes(attrBuilder.build());
            sp = builder.build();
        }
        else {
            sp = new SoundPool(2, AudioManager.STREAM_SYSTEM, 0);
        }

因?yàn)樵贏ndroid中5.0也是API21以后SoundPool已經(jīng)過時(shí)了,所以要判斷

然后用load加載音頻文件,play播放

      int soundId1=sp.load(this,R.raw.winlog,1);
      int soundId2=sp.load(this,R.raw.lesson1,2);
        Button button1=(Button)findViewById(R.id.button1);
        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sp.play(soundId1,1,1,1,0,1);
            }
        });
        Button button2=(Button)findViewById(R.id.button2);
        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sp.play(soundId2,2,1,1,0,1);
            }
        });

SoundPool也有其他的方法,例如

  • pause(),暫停播放

  • release(),釋放SoundPool中加載的音頻資源

  • resume(),繼續(xù)播放暫停的視頻

  • setLoop(),設(shè)置重復(fù)播放次數(shù)

  • setVlume(),設(shè)置音量

  • stop(),停止播放

  • unload(),卸載音頻資源

關(guān)于“Android中如何使用SoundPool播放音頻”這篇文章的內(nèi)容就介紹到這里,感謝各位的閱讀!相信大家對(duì)“Android中如何使用SoundPool播放音頻”知識(shí)都有一定的了解,大家如果還想學(xué)習(xí)更多知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI