转载自:http://ganeshtiwaridotcomdotnp.blogspot.com/2011/12/java-sound-capture-from-microphone.html

Sound  Capture / Record from Microphone and Save : working java source code example

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.TargetDataLine;
/**
* Reads data from the input channel and writes to the output stream
*/
public class MicrophoneRecorder implements Runnable {
// record microphone && generate stream/byte array
private AudioInputStream audioInputStream;
private AudioFormat format;
public TargetDataLine line;
public Thread thread;
private double duration;
public MicrophoneRecorder(AudioFormat format) {
super();
this.format = format;
}
public void start() {
thread = new Thread(this);
thread.setName("Capture");
thread.start();
}
public void stop() {
thread = null;
}
@Override
public void run() {
duration = 0;
line = getTargetDataLineForRecord();
final ByteArrayOutputStream out = new ByteArrayOutputStream();
final int frameSizeInBytes = format.getFrameSize();
final int bufferLengthInFrames = line.getBufferSize() / 8;
final int bufferLengthInBytes = bufferLengthInFrames * frameSizeInBytes;
final byte[] data = new byte[bufferLengthInBytes];
int numBytesRead;
line.start();
while (thread != null) {
if ((numBytesRead = line.read(data, 0, bufferLengthInBytes)) == -1) {
break;
}
out.write(data, 0, numBytesRead);
}
// we reached the end of the stream. stop and close the line.
line.stop();
line.close();
line = null;
// stop and close the output stream
try {
out.flush();
out.close();
} catch (final IOException ex) {
ex.printStackTrace();
}
// load bytes into the audio input stream for playback
final byte audioBytes[] = out.toByteArray();
final ByteArrayInputStream bais = new ByteArrayInputStream(audioBytes);
audioInputStream = new AudioInputStream(bais, format,
audioBytes.length / frameSizeInBytes);
final long milliseconds = (long) ((audioInputStream.getFrameLength()
* 1000) / format.getFrameRate());
duration = milliseconds / 1000.0;
System.out.println(duration);
try {
audioInputStream.reset();
System.out.println("resetting...");
} catch (final Exception ex) {
ex.printStackTrace();
return;
}
}
private TargetDataLine getTargetDataLineForRecord() {
TargetDataLine line;
final DataLine.Info info = new DataLine.Info(TargetDataLine.class, format);
if (!AudioSystem.isLineSupported(info)) {
return null;
}
// get and open the target data line for capture.
try {
line = (TargetDataLine) AudioSystem.getLine(info);
line.open(format, line.getBufferSize());
} catch (final Exception ex) {
return null;
}
return line;
}
public AudioInputStream getAudioInputStream() {
return audioInputStream;
}
public AudioFormat getFormat() {
return format;
}
public void setFormat(AudioFormat format) {
this.format = format;
}
public Thread getThread() {
return thread;
}
public double getDuration() {
return duration;
}
}

Testing Code :
Its better to use gui rather than console to record sound (due to thread start/stop problem)
Here is my console test application for sound record and save:

 public class Testss {
public static void main(String[] args) throws Exception {
//MicrophoneRecorder mr = new MicrophoneRecorder(AudioFormatUtil.getDefaultFormat());
MicrophoneRecorder mr = new MicrophoneRecorder( YOU NEED TO PASS OBJECT OF AudioFormat here);
mr.start();
Thread.sleep(2000);
mr.stop();
//save
WaveData wd = new WaveData();
Thread.sleep(3000);
wd.saveToFile("~tmp", Type.WAVE, mr.getAudioInputStream());
}
}

Code for saving AudioInputStream in WaveData Class : (Full Code Next Time)

   public boolean saveToFile(String name, AudioFileFormat.Type fileType,
AudioInputStream audioInputStream) {
System.out.println("Saving...");
if (null == name || null == fileType || audioInputStream == null) {
return false;
}
File myFile = new File( name+"." + fileType.getExtension());
// reset to the beginnning of the captured data
try {
audioInputStream.reset();
} catch (Exception e) {
return false;
}
int i = 0;
while (myFile.exists()) {
String temp = "" + i + myFile.getName();
myFile = new File(temp);
}
try {
AudioSystem.write(audioInputStream, fileType, myFile);
} catch (Exception ex) {
return false;
}
System.out.println("Saved " + myFile.getAbsolutePath());
return true;
}

问:hi am using above provided code but am getting the fallowing exception
java.lang.Error: Unresolved compilation problem:
The method getDefaultFormat() is undefined for the type AudioFormatUtil

答:

you need to remove

AudioFormatUtil.getDefaultFormat()

and pass an object of AudioFormat in place of "AudioFormatUtil.getDefaultFormat()" from the line below

MicrophoneRecorder mr = new MicrophoneRecorder(AudioFormatUtil.getDefaultFormat());

Please refer to this for detail about AudioFormat :
http://docs.oracle.com/javase/1.4.2/docs/api/javax/sound/sampled/AudioFormat.html

Java Sound Capture from Microphone working code的更多相关文章

  1. java sound初探

    网上关于java sound的正规资源讲解的非常好,本文不再给出示例,主要提供一些好的资源,并说说我的一些理解,用于形成对java sound的整体认识. 一.几个词汇 TTS:text-to-spe ...

  2. eclipse启动不了,出现“Java was started but returned exit code=13......”对话框

    eclipse启动不了,出现"Java was started but returned exit code=13......"对话框如下 解决方案:1.使用的是java jdk6 ...

  3. eclipse启动时报告错误:Java was started but returned exit code=-805306369

    这两天也没改过eclipse和java的配置,但eclipse启动时报告错误:Java was started but returned exit code=-805306369 后来在eclipse ...

  4. 当我们安装使用时,会出现eclipse启动不了,出现“Java was started but returned exit code=13......”的问题

    安装win8.1后,启动eclipse,也会提示 "java was started but returned exit code=13" 可能是eclipse.ini配置文件错误 ...

  5. Java was started but returned exit code=13 C:\ProgramData\Oracle\Java\javapath\javaw.exe

    ---------------------------Eclipse---------------------------Java was started but returned exit code ...

  6. Eclipse启动报错Java was started but returned exit code=13

    启动Eclipse的时候报错Java was started but returned exit code=13,这个错误的原因是由于eclipse版本与jdk版本不符导致的,可能你的eclipse是 ...

  7. myeclipse启动报“java was started but returned exit code=13”

    在win8系统中的myeclipse拷贝到win7系统中后,解压缩打开提示"java was started but returned exit code=13", 可能是myec ...

  8. Java was started but returned exit code=13

    安装Eclipse(32位)后打开报错:Java was started but returned exit code=13 解决方法: 1,首先我查看了我当前安装的JDK版本,发现是64位的: 2, ...

  9. MyEclipse java was started but returned exit code=-1

    java was started but returned exit code=-1 Vm指的是java虚拟机,默认你安装MyEclipse时会自带一个java虚拟机,Vm配置那一行换成你安装的jav ...

随机推荐

  1. Linux 安装网络yum地址

    rpm -Uhv http://dl.fedoraproject.org/pub/epel/6/x86_64/epel-release-6-8.noarch.rpm   rpm -Uhv http:/ ...

  2. Python函数的基本使用

    在编程中,无论使用什么 编程语言,函数的使用都是非常广泛的,函数能够完成特定的功能,降低编程的难度和代码重用. 1.函数的定义: 函数是一段具有特定功能的.可重用的语句组,用函数名来表示并通过函数名进 ...

  3. sublime test 3 配置安装fortran开发环境

    1.ST3下安装包管理工具Package Control https://jingyan.baidu.com/article/3c343ff7dca2b10d3779633b.html ST主界面下c ...

  4. Oracle plsql存储过程中out模式参数的用法

    在plsql中,存储过程中的out模式的参数可以用来返回数据,相当于函数的返回值.下面是一个小例子. 沿用上一篇的emp表结构和数据. 存储过程如下: create or replace proced ...

  5. MongoDB collection Index DB 大小查询

    1.collection中的数据大小 db.collection.dataSize() 2.为collection分配的空间大小,包括未使用的空间db.collection.storageSize() ...

  6. TFRecord 使用

    tfrecord生成 import os import xmltodict import tensorflow as tf import numpy as np dir_path = 'F:\数据存储 ...

  7. 16、job触发流程原理剖析与源码分析

    一.以Wordcount为例来分析 1.Wordcount val lines = sc.textFile() val words = lines.flatMap(line => line.sp ...

  8. Angular惰性加载的特性模块

    一:Angular-CLI建立应用 cmd命令:ng new lazy-app --routing    (创建一个名叫 lazy-app 的应用,而 --routing 标识生成了一个名叫 app- ...

  9. UOJ#470. 【ZJOI2019】语言 虚树,线段树合并

    原文链接www.cnblogs.com/zhouzhendong/p/UOJ470.html 前言 做完情报中心来看这个题突然发现两题有相似之处然后就会做了. 题解 首先,我们考虑将所有答案点对分为两 ...

  10. Django REST framework优点?

    1.提供了定义序列化器Serializer的方法,可以快速根据Django ORM 或者其他库自动序列化/反序列化2.提供了丰富的类视图\MIXIN扩展类,简化视图的编写3.丰富的定制层级:函数视图\ ...