gpt4 book ai didi

java - 如何在Java中以给定的采样率播放声音?

转载 作者:行者123 更新时间:2023-12-02 11:17:49 25 4
gpt4 key购买 nike

我想知道是否有一个库或其他东西可以以给定的采样率(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);

}
}

来源:http://www.rgagnon.com/javadetails/java-0499.html

关于java - 如何在Java中以给定的采样率播放声音?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23096533/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com