Android如何給按鈕添加點擊音效
有很多制作精良的APP都自帶點擊音效,那么如何簡單的來實現(xiàn)這一效果,這里需要使用到的一個概念叫做SoundPool,這個類主要用于播放一些比較小的音頻文件,因為比較方便,通常用在游戲里比較多。
代碼
閑話不多說,我們現(xiàn)在需要做一個功能,就是點擊某一按鈕的時候同時播放音效出來。
首先準備好你的音頻文件,然后,在你的rec下面簡歷一個文件夾命名為raw,放入音頻文件,如圖所示:

然后布局文件只有一個按鈕
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="@+id/btnPlay"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_margin="5dp"
android:text="Play Wav"
tools:ignore="HardcodedText" />
</LinearLayout>
然后是MainActivity
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button btnPlay;
private SoundPool soundPool;//聲明一個SoundPool
private int soundID;//創(chuàng)建某個聲音對應的音頻ID
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
btnPlay = (Button) findViewById(R.id.btnPlay);
btnPlay.setOnClickListener(this);
initSound();
}
@SuppressLint("NewApi")
private void initSound() {
soundPool = new SoundPool.Builder().build();
soundID = soundPool.load(this, R.raw.testsong, 1);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnPlay:
playSound();
break;
}
}
private void playSound() {
soundPool.play(
soundID,
0.1f, //左耳道音量【0~1】
0.5f, //右耳道音量【0~1】
0, //播放優(yōu)先級【0表示最低優(yōu)先級】
1, //循環(huán)模式【0表示循環(huán)一次,-1表示一直循環(huán),其他表示數(shù)字+1表示當前數(shù)字對應的循環(huán)次數(shù)】
1 //播放速度【1是正常,范圍從0~2】
);
}
}
這樣當你點擊按鈕的時候就會自動播放音效,要注意,這里初始化SoundPool的方法是安卓5.0以后提供的新方式,5.0以前的話可以使用:
soundPool = new SoundPool(5, AudioManager.STREAM_MUSIC, 0);
其中構(gòu)造方法放參數(shù)不在解釋,隨著安卓的發(fā)展,5.0之前的份額也會越來越少,所以在以后的文中盡量使用比較新的SDK提供的方法。
以上代碼完成后在手機上運行,點擊可以聽到音效。
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Material Design系列之Behavior實現(xiàn)支付密碼彈窗和商品屬性選擇效果
這篇文章主要為大家詳細介紹了Material Design系列之Behavior實現(xiàn)支付密碼彈窗和商品屬性選擇效果,具有一定的參考價值,感興趣的小伙伴們可以參考一下2016-09-09
Android ndk獲取手機內(nèi)部存儲卡的根目錄方法
今天小編就為大家分享一篇Android ndk獲取手機內(nèi)部存儲卡的根目錄方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-08-08

