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 ...
随机推荐
- ES的入门学习
ES的入门:ES的雇员文档的设计和实现功能 ES的存放中包括:索引,类型,文档,字段 PUT /megacorp/employee/1{{ "first_name" : " ...
- netty: 将传递数据格式转为String,并使用分隔符发送多条数据
自定义分割符,用:DelimiterBasedFrameDecoder类 ByteBuf转String,用StringDecoder类 参考代码: //设置连接符/分隔符,换行显示 ByteBuf b ...
- LightOJ - 1259 - Goldbach`s Conjecture(整数分解定理)
链接: https://vjudge.net/problem/LightOJ-1259 题意: Goldbach's conjecture is one of the oldest unsolved ...
- 基于Python3+Requests的贴吧签到助手
因为总是忘记签到,所以尝试写了一个签到脚本,因为使用的是Python3,所以没法使用Urllib2,于是选择了Requests,事实证明,Requests比Urllib2好用.整体思路比较简单,就是模 ...
- SIGAI机器学习第二十集 AdaBoost算法1
讲授Boosting算法的原理,AdaBoost算法的基本概念,训练算法,与随机森林的比较,训练误差分析,广义加法模型,指数损失函数,训练算法的推导,弱分类器的选择,样本权重削减,实际应用 AdaBo ...
- Magma中ECC的点乘实例
a:=-3;b:= 41058363725152142129326129780047268409114441015993725554835256314039467401291;E:= Elliptic ...
- webbench 源代码
WebBench源码:https://github.com/EZLippi/WebBench Webbench是一个在linux下使用的非常简单的网站压测工具.它使用fork()模拟多个客户端同时访问 ...
- ZR#1015
ZR#1015 解法: 我们需要求得, $ g_i $ 表示长度为的最长不下降子序列个数. 设 $ f_{i,j} $ 表示统计第前$ i $ 个数字,得到最长不下降子序列末端为 $ j $ . 显然 ...
- 【洛谷】P3177 [HAOI2015]树上染色
懒得复制题面了直接传送门吧 分析 直接求点与点之间的距离感觉不是很好求,所以我们考虑换一个求法. 瞄了一眼题解 距离跟路径上边的长度有关,所以我们直接来看每一条边的贡献吧(这谁想得到啊) 对于每一条边 ...
- Spring Boot|监控-Actuator
Spring Boot 为我们提供了一个生产级特性-Actuator,包含很多实际有用的API,下面我们就一起来看看这些API. 一.Actuator 首先在程序中引入Actuator <!-- ...