<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/ll1" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="horizontal" > <Button android:id="@+id/dog" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="狗叫"/> <Button android:id="@+id/brid" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="鸟叫"/> <Button android:id="@+id/notify" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="闹铃声"/> <Button android:id="@+id/laugh" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="笑声"/> </LinearLayout>
package com.example.test; import java.util.HashMap; import android.app.Activity; import android.media.AudioManager; import android.media.SoundPool; import android.os.Bundle; import android.view.KeyEvent; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; public class MainActivity extends Activity{ private SoundPool soundpool;//声明一个SoundPool对象 private HashMap<Integer,Integer> soundmap=new HashMap<Integer,Integer>();//创建一个HashMap对象 @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); //创建一个SoundPool对象,该对象可以容纳5个音频流 soundpool=new SoundPool(5,AudioManager.STREAM_MUSIC,0); //将要播放的音频流保存到HashMap对象中 soundmap.put(1,soundpool.load(this, R.raw.dog,1)); soundmap.put(2,soundpool.load(this, R.raw.brid,1)); soundmap.put(3,soundpool.load(this, R.raw.notify,1)); soundmap.put(4,soundpool.load(this, R.raw.laugh,1)); soundmap.put(5,soundpool.load(this, R.raw.ding,1)); Button dog=(Button)findViewById(R.id.dog); dog.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { soundpool.play(soundmap.get(1), 1,1,0,0,1); } }); Button brid=(Button)findViewById(R.id.brid); brid.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { soundpool.play(soundmap.get(2), 1,1,0,0,1); } }); Button notify=(Button)findViewById(R.id.notify); notify.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { soundpool.play(soundmap.get(3), 1,1,0,0,1); } }); Button laugh=(Button)findViewById(R.id.laugh); laugh.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { soundpool.play(soundmap.get(4), 1,1,0,0,1); } }); } //重写键盘被按下的onKeyDown()方法,用于实现播放按键音的功能 @Override public boolean onKeyDown(int keyCode, KeyEvent event) { soundpool.play(soundmap.get(5), 1,1,0,0,1);//播放按键音 return true; } }
运行结果如图
转载请注明出处:http://blog.csdn.net/acmman/article/details/46551047