Java Sound Capture from Microphone working code
转载自: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的更多相关文章
- java sound初探
网上关于java sound的正规资源讲解的非常好,本文不再给出示例,主要提供一些好的资源,并说说我的一些理解,用于形成对java sound的整体认识. 一.几个词汇 TTS:text-to-spe ...
- eclipse启动不了,出现“Java was started but returned exit code=13......”对话框
eclipse启动不了,出现"Java was started but returned exit code=13......"对话框如下 解决方案:1.使用的是java jdk6 ...
- eclipse启动时报告错误:Java was started but returned exit code=-805306369
这两天也没改过eclipse和java的配置,但eclipse启动时报告错误:Java was started but returned exit code=-805306369 后来在eclipse ...
- 当我们安装使用时,会出现eclipse启动不了,出现“Java was started but returned exit code=13......”的问题
安装win8.1后,启动eclipse,也会提示 "java was started but returned exit code=13" 可能是eclipse.ini配置文件错误 ...
- Java was started but returned exit code=13 C:\ProgramData\Oracle\Java\javapath\javaw.exe
---------------------------Eclipse---------------------------Java was started but returned exit code ...
- Eclipse启动报错Java was started but returned exit code=13
启动Eclipse的时候报错Java was started but returned exit code=13,这个错误的原因是由于eclipse版本与jdk版本不符导致的,可能你的eclipse是 ...
- myeclipse启动报“java was started but returned exit code=13”
在win8系统中的myeclipse拷贝到win7系统中后,解压缩打开提示"java was started but returned exit code=13", 可能是myec ...
- Java was started but returned exit code=13
安装Eclipse(32位)后打开报错:Java was started but returned exit code=13 解决方法: 1,首先我查看了我当前安装的JDK版本,发现是64位的: 2, ...
- MyEclipse java was started but returned exit code=-1
java was started but returned exit code=-1 Vm指的是java虚拟机,默认你安装MyEclipse时会自带一个java虚拟机,Vm配置那一行换成你安装的jav ...
随机推荐
- set_index
Signature: df.set_index( ['keys', 'drop=True', 'append=False', 'inplace=False', 'verify_integrity=Fa ...
- js select 默认回显判断
<select id="dataselect" class="input-medium" style="width: 20%"> ...
- python 中 super函数的使用
转载地址:http://python.jobbole.com/86787/ 1.简单的使用 在类的继承中,如果重定义某个方法,该方法会覆盖父类的同名方法,但有时,我们希望能同时实现父类的功能,这时,我 ...
- python同时取每个列表的第一个元素
在实际爬虫开发中, 经常用到列表保存数据, 在使用这些数据的时候,需要要取每个列表里的第一个元素进行拼接. 就需要用到python的内置方法:“zip()" # 现在有3个列表:li_1, ...
- POJ 2778 DNA Sequence (矩阵快速幂 + AC自动鸡)
题目:传送门 题意: 给你m个病毒串,只由(A.G.T.C) 组成, 问你生成一个长度为 n 的 只由 A.C.T.G 构成的,不包含病毒串的序列的方案数. 解: 对 m 个病毒串,建 AC 自动机, ...
- Day12:H5
掌握HTML+CSS+JavaScript相关知识 了解HTML5的结构标签: 掌握新增和删去的标签及相关属性 运用HTML5相关知识进行实际开发 下面哪种语法中是对大小写进行区分的? XHTML H ...
- IDEA中常用快捷键
Alt+Enter 牛掰的万能快捷键,实现接口和抽象类.导入包.异常捕获.转换lambda表达式.equals的翻转和更换访问修饰符等,无所不能. Ctrl+D 复制当前行 Ctrl+Y 删除行 ...
- WEB甘特图(机器运行状态图)
前台框架使用BootStrap轻量级框架AdminLTE 后台框架使用的是Spring.SpringMVC 初此使用数据库SQL Server故只能用JDBC连接 请勿见怪!jsp页面重复添加元素过多 ...
- eclipse快捷键及设置【转】
1.Eclipse设置新建菜单初始项 windows-->Perspective-->Customize Perspective--> 2.Eclipse快捷键 1. ctrl+sh ...
- 我为什么选择Vim
总看到一些飞快敲击键盘而不用鼠标的时候你可以很羡慕和佩服,其实这完全没有必要.就像一个吉他手熟练地弹吉他有必要羡慕吗?一个瓦匠熟练地砌砖有必要羡慕吗?这些都是他们赖以生存的工具而已,熟练地运用工具是理 ...