【发布时间】:2014-04-15 23:50:12
【问题描述】:
我想知道是否有库或其他东西可以在给定的采样率(20-20,000 Hz)上播放声音。实际上,我找到了something,但我不明白如何让它工作!
【问题讨论】:
我想知道是否有库或其他东西可以在给定的采样率(20-20,000 Hz)上播放声音。实际上,我找到了something,但我不明白如何让它工作!
【问题讨论】:
这是不需要任何外部库的完整示例:
import javax.sound.sampled.*;
public class SoundUtils {
public static float SAMPLE_RATE = 8000f;
public static void tone(int hz, int msecs)
throws LineUnavailableException
{
tone(hz, msecs, 1.0);
}
public static void tone(int hz, int msecs, double vol)
throws LineUnavailableException
{
byte[] buf = new byte[1];
AudioFormat af =
new AudioFormat(
SAMPLE_RATE, // sampleRate
8, // sampleSizeInBits
1, // channels
true, // signed
false); // bigEndian
SourceDataLine sdl = AudioSystem.getSourceDataLine(af);
sdl.open(af);
sdl.start();
for (int i=0; i < msecs*8; i++) {
double angle = i / (SAMPLE_RATE / hz) * 2.0 * Math.PI;
buf[0] = (byte)(Math.sin(angle) * 127.0 * vol);
sdl.write(buf,0,1);
}
sdl.drain();
sdl.stop();
sdl.close();
}
public static void main(String[] args) throws Exception {
SoundUtils.tone(1000,100);
Thread.sleep(1000);
SoundUtils.tone(100,1000);
Thread.sleep(1000);
SoundUtils.tone(5000,100);
Thread.sleep(1000);
SoundUtils.tone(400,500);
Thread.sleep(1000);
SoundUtils.tone(400,500, 0.2);
}
}
【讨论】:
SoundUtils.tone(400,500, 0.2);
SoundUtils 是作者在其示例中创建的类的名称(参见示例开头的public class SoundUtils {)。您可以按原样重用这个类,就像您在示例底部的 main 方法中看到的那样。
a sound(你能证明别的吗?)并且按照要求做。对吗?
open() 被调用来获取系统的“声音”资源。这类似于在对文件进行读取或写入之前打开文件。是的,它是一个真正的正弦波。以下是 1Khz 频率的 buf[] 内容示例:0, 89, 127, 89, 0, -89, -127, -89, 0, ...
file = open(name); open(file); 是典型的吗?读/写在哪里?关于正弦波,我不想知道它是否真实。我很想知道问题中要求的声音如何?