本文共 3877 字,大约阅读时间需要 12 分钟。
MainActivity:
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 HashMapsoundmap=new HashMap ();//创建一个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; }}
运行结果如图
转载请注明出处: