package com.zzl.test; import java.util.HashMap; import java.util.Map; import android.app.Activity; import android.media.AudioManager; import android.media.SoundPool; import android.media.ToneGenerator; import android.os.Bundle; import android.view.KeyEvent; import android.view.View; import android.view.View.OnKeyListener; import android.widget.EditText; public class MainActivity extends Activity { private SoundPool soundPool; MapsoundMap = new HashMap (); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); EditText et = (EditText) findViewById(R.id.et_test); soundPool = new SoundPool(10, AudioManager.STREAM_SYSTEM, 5); addVoice(); et.setOnKeyListener(new OnKeyListener() { @Override public boolean onKey(View arg0, int arg1, KeyEvent arg2) { play(arg1); return false; } }); } /** * 添加语音文件 * raw文件夹下的a代表0、b代表1.。。。。。。。。。 */ public void addVoice(){ soundMap.put(0, soundPool.load(MainActivity.this, R.raw.a, 1)); soundMap.put(1, soundPool.load(MainActivity.this, R.raw.b, 1)); soundMap.put(2, soundPool.load(MainActivity.this, R.raw.c, 1)); soundMap.put(3, soundPool.load(MainActivity.this, R.raw.d, 1)); soundMap.put(4, soundPool.load(MainActivity.this, R.raw.e, 1)); soundMap.put(5, soundPool.load(MainActivity.this, R.raw.f, 1)); soundMap.put(6, soundPool.load(MainActivity.this, R.raw.g, 1)); soundMap.put(7, soundPool.load(MainActivity.this, R.raw.h, 1)); soundMap.put(8, soundPool.load(MainActivity.this, R.raw.i, 1)); soundMap.put(9, soundPool.load(MainActivity.this, R.raw.j, 1)); } /** * 播放声音文件 * */ public void play(int id) { switch (id) { case 7: soundPool.play(soundMap.get(0), 1, 1, 1, 0, 1); break; case 8: soundPool.play(soundMap.get(1), 1, 1, 1, 0, 1); break; case 9: soundPool.play(soundMap.get(2), 1, 1, 1, 0, 1); break; case 10: soundPool.play(soundMap.get(3), 1, 1, 1, 0, 1); break; case 11: soundPool.play(soundMap.get(4), 1, 1, 1, 0, 1); break; case 12: soundPool.play(soundMap.get(5), 1, 1, 1, 0, 1); break; case 13: soundPool.play(soundMap.get(6), 1, 1, 1, 0, 1); case 14: soundPool.play(soundMap.get(7), 1, 1, 1, 0, 1); break; case 15: soundPool.play(soundMap.get(8), 1, 1, 1, 0, 1); break; case 16: soundPool.play(soundMap.get(9), 1, 1, 1, 0, 1); break; default: break; } } }
记得在res/raw文件夹下放入语音文件