Zi 字媒體
2017-07-25T20:27:27+00:00
首先要準備一個不超過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 學習總集
寫了
5860316篇文章,獲得
23313次喜歡