search
尋找貓咪~QQ 地點 桃園市桃園區 Taoyuan , Taoyuan

[Android] SoundPool 系統提示音效 @ Saioyan梟夜 :: 痞客邦 ::

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

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

接著就進入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 程式設計教學

 



熱門推薦

本文由 kk665403pixnetnetblog 提供 原文連結

寵物協尋 相信 終究能找到回家的路
寫了7763篇文章,獲得2次喜歡
留言回覆
回覆
精彩推薦