您的位置:首页 > 移动开发 > Android开发

给按钮点击事件添加音效;

2017-02-10 15:44 537 查看
编写布局文件只添加一个button;

<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"

tools:context="com.example.test4.MainActivity" >

<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />

</LinearLayout>


编写代码;

package com.example.test4;

import android.app.Activity;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;

public class MainActivity extends Activity {
private Button button ;
private SoundPool sPool;//声明一个sPool
private int music;//定义一个整型用load();来设置suondID
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

button =(Button) findViewById(R.id.button1);
sPool =new SoundPool(10, AudioManager.STREAM_SYSTEM, 5);//第一个参数为同时播放数据流的最大个数,第二数据流类型,第三为声音质量
music=sPool.load(this, R.raw.aaa, 1);//把你的声音素材放到res/raw里,第2个参数即为资源文件,第3个为音乐的优先级
button.setOnClickListener( new OnClickListener() {

@Override
public void onClick(View v) {
sPool.play(music, 1, 1, 0, 0, 1);
}
});
//
}

}


3.点击提交按钮,就会自动播放, /src/raw文件夹下的aaa.mp3音乐文件
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息