[Android] SoundPool 系統提示音效

更新 發佈閱讀 5 分鐘


首先要準備一個不超過1MB的音頻檔案

在res裡面新增一個資料夾放置

raw-image


raw-image


接著就進入Code的環節,以下CODE請自行修改載入的音頻檔案

示範

XML

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<Button
android:id="@+id/b1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="sound"
android:text="音效"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

JAVA

public class MainActivity extends AppCompatActivity {
private SoundPool soundPool;//宣告
private int soundID;//創建音頻ID
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Android SDK version 要大於21才能使用
if (Build.VERSION.SDK_INT >= 21) {
soundPool = new SoundPool.Builder().build();
soundID = soundPool.load(MainActivity.this, R.raw.music1, 1);//載入音頻檔案
}
}
private void sound() {
soundPool.play(
soundID,
0.5f, //左耳道音量0~1
0.5f, //右耳道音量0~1
0, //播放優先權
0, //循環模式0是1次,-1是無限次,0以上就是n+1次
1 //撥放速度0~2
);
}
public void sound(View v){
sound();
}
}

相關文章:

[Android] Android 程式設計教學

本網站https://kk665403.pixnet.net/內之全部圖文,Saioyan梟夜所有,非經本人同意不得將全部或部分內容轉載於任何形式之媒體
Copyright © 2021 Saioyan. All rights reserved.
版權所有© 2021 Saioyan梟夜

留言
avatar-img
Saioyan的沙龍
34會員
909內容數
贊助我 https://vocus.cc/pay/donate/@kk665403?donateSourceType=exclusiveLink
Saioyan的沙龍的其他內容
2018/10/05
示範 XML <?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android
2018/10/05
示範 XML <?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android
2018/10/05
一般來說我們使用到AlertDialog頂多是寫個文字或是改改標題 但如果想往AlertDialog裡面擺放其他的元件該怎麼辦呢? 比如說我想讓對話窗裡面顯示一個小星星之類的,如下圖 我們會使用到LayoutInflater,View來加載外部的布局(layout) 示範 XML 首
Thumbnail
2018/10/05
一般來說我們使用到AlertDialog頂多是寫個文字或是改改標題 但如果想往AlertDialog裡面擺放其他的元件該怎麼辦呢? 比如說我想讓對話窗裡面顯示一個小星星之類的,如下圖 我們會使用到LayoutInflater,View來加載外部的布局(layout) 示範 XML 首
Thumbnail
2018/10/05
AlertDialog 複數對話窗呼叫就是在初始對話窗內的按鈕按下後呼叫另一個對話窗出來 兩對話窗就可以交互切換使用,可用於放置不同的資料或圖片之類的訊息 如下圖所示 要達到此效果只要在對話窗裡面互相調用Code即可 示範 XML <?xml version="1.0" enco
Thumbnail
2018/10/05
AlertDialog 複數對話窗呼叫就是在初始對話窗內的按鈕按下後呼叫另一個對話窗出來 兩對話窗就可以交互切換使用,可用於放置不同的資料或圖片之類的訊息 如下圖所示 要達到此效果只要在對話窗裡面互相調用Code即可 示範 XML <?xml version="1.0" enco
Thumbnail
看更多