java - Java - 从 TargetDataLine 读取音频 - 只读取零/
问题描述
我在使用 TargetDataLine 时遇到问题 - 它一直从混音器中读取零。
以下是使用完美工作的arecord:
arecord -D plughw:1,0,0 -r 44100 -f s16_le -c 2 -d 3 /tmp/file.wav
当我用 javax.sound.sampled 尝试这个时,我总是得到零。以下使用线程打开 TargetDataLine 以在 5 秒后停止读取。读取缓冲区始终用零填充。
package com.example;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.Mixer;
import javax.sound.sampled.TargetDataLine;
import javax.sound.sampled.Mixer.Info;
public class AudioTest {
static final long RECORD_TIME = 5000;
private TargetDataLine line;
private boolean isRecording = false;
private void run() {
Thread stopper = new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(RECORD_TIME);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
System.out.println("\nSleep for " + RECORD_TIME + " complete - attempting to end");
finish();
}
});
stopper.start();
try {
AudioFormat format = new AudioFormat(44100, 16, 2, true, false);
Info[] infos = AudioSystem.getMixerInfo();
int mixerNumber = 3; // This is the one that matches the one that works with arecord.
Mixer mixer = AudioSystem.getMixer(infos[mixerNumber]);
System.out.println("Using infos " + mixerNumber + ", " + infos[mixerNumber].getName() + ", " +infos[mixerNumber].getDescription());
System.out.println("Using format to open TargetDataLine: " + format.toString());
DataLine.Info info = new DataLine.Info(TargetDataLine.class, format);
line = (TargetDataLine)mixer.getLine(info);
int BUFFER_SIZE = 2048;
byte[] bytesBuffer = new byte[BUFFER_SIZE];
int bytesRead = -1;
line.open(format);
isRecording = true;
while (((bytesRead = line.read(bytesBuffer, 0 , BUFFER_SIZE)) != -1) && (isRecording)) {
if (bytesRead != 0)
System.out.println("Read Something - yeah");
}
System.out.println("");
} catch (Exception e) {
e.printStackTrace();
}
}
private void finish() {
line.stop();
line.close();
isRecording = false;
}
public static void main(String[] args) {
AudioTest audioTest = new AudioTest();
audioTest.run();
}
}
输出通常如下所示:
Using infos 3, Loopback [plughw:1,0], Direct Audio Device: Loopback, Loopback PCM, Loopback PCM
Using format to open TargetDataLine: PCM_SIGNED 44100.0 Hz, 16 bit, stereo, 4 bytes/frame, little-endian
Sleep for 5000 complete - attempting to end
logout
有什么明显的我想念的吗-谢谢
解决方案
推荐阅读
- ruby-on-rails - Ruby on rails 连接到正确的 Postgres DB
- algorithm - sagemaker 的线性学习器可以用于多类分类吗?
- wordpress - 任何显示我网站上所有断开链接的 WordPress 插件?
- algorithm - 合并排序双向链表
- android - 无法使用 Volley 将数据从 android 发布到 api
- jquery - Flot 多折线图,其中类别不显示标签
- php - Laravel 5.6 Symfony \ Component \ Debug \ Exception \ FatalThrowableError(E_ERROR)类'\ App \ Utilisateurs'未找到
- angular - 如何在angular2中验证新密码并确认密码
- git - 如何修复:致命:无效的反向引用
- encryption - 低功耗蓝牙连接中的 LTK 是如何形成的?