gpt4 book ai didi

java - 频率音调发生器播放错误的声音

转载 作者:行者123 更新时间:2023-11-29 21:46:45 28 4
gpt4 key购买 nike

我在生成特定频率的声音时遇到了一些问题。我已经设置了我的应用程序,因此您可以在搜索栏上来回滑动以选择特定频率,然后该应用程序应使用该频率来生成音调。

我目前听到的音调很好,但它的频率与您设置的频率完全不同。 (而且我知道问题不在于将值从搜索栏传递到“音调生成过程”,所以它一定是我生成音调的方式。)

这段代码有什么问题?谢谢

private final int duration = 3; // seconds
private final int sampleRate = 8000;
private final int numSamples = duration * sampleRate;
private final double sample[] = new double[numSamples];
double dbFreq = 0; // I assign the frequency to this double
private final byte generatedSnd[] = new byte[2 * numSamples];

...


void genTone(double dbFreq){

// fill out the array
for (int i = 0; i < numSamples; ++i) {
sample[i] = Math.sin(2 * Math.PI * i / (sampleRate/dbFreq));
}

// convert to 16 bit pcm sound array
// assumes the sample buffer is normalised.
int idx = 0;
for (final double dVal : sample) {
// scale to maximum amplitude
final short val = (short) ((dVal * 32767));
// in 16 bit wav PCM, first byte is the low order byte
generatedSnd[idx++] = (byte) (val & 0x00ff);
generatedSnd[idx++] = (byte) ((val & 0xff00) >>> 8);
}
}

void playSound(){
final AudioTrack audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC,
sampleRate, AudioFormat.CHANNEL_CONFIGURATION_MONO,
AudioFormat.ENCODING_PCM_16BIT, numSamples,
AudioTrack.MODE_STATIC);
audioTrack.write(generatedSnd, 0, generatedSnd.length);
audioTrack.play();
}

最佳答案

您的代码实际上是正确的但是看看Sampling theorem .

简而言之:您必须将采样率设置为高于 2*max_frequency。因此,设置 sampleRate = 44000,您应该可以正确听到更高的频率。

关于java - 频率音调发生器播放错误的声音,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15578468/

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