Java中如何合成声音?
我正在尝试在 Ubuntu 11.10 笔记本电脑上用 Java 编写自定义合成器。这是我的代码:
package com.sibbo.audio;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.Clip;
import javax.sound.sampled.LineUnavailableException;
public class Audio {
public static void main(String[] args) throws LineUnavailableException {
byte[] data = new byte[16000 * 2];
sinus(data);
AudioFormat format = new AudioFormat(16000, 8, 1, true, true);
Clip c = javax.sound.sampled.AudioSystem.getClip();
c.open(format, data, 0, data.length); // throws IllegalArgumentException
}
private static void sinus(byte[] data) {
for (int i = 0; i < data.length; i++) {
data[i] = (byte) (Math.sin(i / 200.0) * 127);
}
}
}
在标记行处,它抛出异常,说:“格式无效”。如何确定哪些音频格式是合法的?我已经尝试过切换有符号/无符号和小/大尾数的布尔值。
I'm trying to write a custom synthesizer in Java on a Ubuntu 11.10 laptop. Here is my code:
package com.sibbo.audio;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.Clip;
import javax.sound.sampled.LineUnavailableException;
public class Audio {
public static void main(String[] args) throws LineUnavailableException {
byte[] data = new byte[16000 * 2];
sinus(data);
AudioFormat format = new AudioFormat(16000, 8, 1, true, true);
Clip c = javax.sound.sampled.AudioSystem.getClip();
c.open(format, data, 0, data.length); // throws IllegalArgumentException
}
private static void sinus(byte[] data) {
for (int i = 0; i < data.length; i++) {
data[i] = (byte) (Math.sin(i / 200.0) * 127);
}
}
}
At the marked line, it throws an Exception, saying: "Invalid format". How can I figure out which AudioFormats are legal? What I already tried is switching the boolean values for signed/unsigned and little/big endian.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为错误消息的意思是相反的。它并不是抱怨系统不支持 AudioFormat,而是它无法将您的数据解析为这种格式。来自 Javadoc:
I think the error message is meant the other way around. It is not complaining about the AudioFormat not being supported by the system, but instead it cannot parse your data into this format. From the Javadoc:
一年后我也遇到同样的问题不过,我想通了一些事情;假设 c.getInfo() 返回 DataLine.Info,以下给出了支持的格式:
由于某种原因,我的只有一种支持的格式,这有点奇怪。另外,我遵循了代码,并且使用不在支持列表中的 AudioFormat 确实会给您错误“格式无效”。
I'm having the same problem, a year later. I figured out something, though; under the assumption that c.getInfo() returns a DataLine.Info, the following gives the supported formats:
For some reason, mine only has one supported format, and it's kinda weird. Also, I followed the code, and using an AudioFormat not in the supported list does give you the error "Invalid format."