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 ...
随机推荐
- Java邮件开发(三):解决附件名为乱码及显示友好名称
1.附件的名称只能为英文,中文乱码 2.友好名称的显示. 我们使用163等邮箱发送邮件时,我们经常可以看到收件人一栏中会是:张益达 <zyh5540@163.com>这种方式.在上一版本的 ...
- Tensorflow细节-P84-梯度下降与批量梯度下降
1.批量梯度下降 批量梯度下降法是最原始的形式,它是指在每一次迭代时使用所有样本来进行梯度的更新.从数学上理解如下: 对应的目标函数(代价函数)即为: (1)对目标函数求偏导: (2)每次迭代对参数进 ...
- CF827D Best Edge Weight 题解
题意: 给定一个点数为 n,边数为 m,权值不超过 \(10^9\) 的带权连通图,没有自环与重边. 现在要求对于每一条边求出,这条边的边权最大为多少时,它还能出现在所有可能的最小生成树上,如果对于任 ...
- python与各数据库的交互
from redis import StrictRedis from pymongo import MongoClient import pymysql #redis客户端 redis_cli = S ...
- Linux 用户和用户组管理之 修改用户名和用户组;修改用户密码
一.用户账号包括(查看已经存在的账号 | 添加用户账号 | 修改用户账号 | 删除用户账号) 查看存在的账号: more /etc/passwd #或者是 awk -F':' '{ print $1 ...
- leetcode解题报告(25):Reverse Words in a String III
描述 Given a string, you need to reverse the order of characters in each word within a sentence while ...
- spark sql 常用语句
在spark dataFrame数据结构里面使用sql语句查询数据 (因为是RDD和dataFrame数据是只读的,所以不能做修改,删除操作.) 首先将文本数据转换为DataFrame数据格式 有两种 ...
- for循环实战性能优化之使用Map集合优化
笔者在<for循环实战性能优化>中提出了五种提升for循环性能的优化策略,这次我们在其中嵌套循环优化小循环驱动大循环的基础上,借助Map集合高效的查询性能来优化嵌套for循环 ...
- Java中对象并不是都在堆上分配内存的
转(https://blog.51cto.com/13906751/2153924) 前段时间,给星球的球友们专门码了一篇文章<深入分析Java的编译原理>,其中深入的介绍了Java中的j ...
- arcpy SearchCursor sql_clause
import arcpy fc = 'c:/data/base.gdb/well' fields = ['WELL_ID', 'WELL_TYPE'] # Use ORDER BY sql claus ...