Android 之 声音捕捉
声音捕捉、就是当外界声音达到一定的峰值以后,触发调用这个函数。
代码如下:
需要注意的是cachePath值,因为android的系统文件的目录是不允许乱写的,所以你要指定你自己程序的存储目录。
cachePath的设置可以参考:乘坐太空船~
1 try { 2 File soundFile = new File(cachePath+"audio.3gp"); 3 4 if(mRecorder == null){ 5 mRecorder = new MediaRecorder(); 6 mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC); 7 mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP); 8 mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB); 9 mRecorder.setOutputFile(soundFile.getAbsolutePath()); 10 } 11 mRecorder.prepare(); 12 mRecorder.start(); 13 } catch (IOException e) { 14 e.printStackTrace(); 15 } 16 CheckMicophoneVolume thread = new CheckMicophoneVolume(); 17 thread.start();
需要一个不停检测外部声音的线程,当声音达到峰值,停止线程,通知相关事件处理。
1 private static class CheckMicophoneVolume extends Thread { 2 private volatile boolean running = true; 3 4 public void exit() { 5 running = false; 6 } 7 8 @Override 9 public void run() { 10 while (running) { 11 try { 12 Thread.sleep(200); 13 } catch (InterruptedException e) { 14 e.printStackTrace(); 15 } 16 17 if (mRecorder == null || !running) { 18 break; 19 } 20 21 int x = mRecorder.getMaxAmplitude(); 22 Log.v("X_value", ""+x); 23 if (x != 0) { 24 int f = (int) (10 * Math.log(x) / Math.log(10)); 25 Log.v("value", ""+f); 26 if (f > 40) { 27 catchVoiceSuccess(); 28 exit(); 29 } 30 } 31 } 32 } 33 }