我在生成特定频率的声音时遇到了一些麻烦。我已经设置了我的应用程序,因此您可以在搜索栏上来回滑动以选择特定频率,应用程序应该使用该频率生成音调。
我目前的音调很好,但它与你设定的频率完全不同。 (我知道问题不是将值从搜索栏传递到“音调生成过程”,所以它必须是我产生音调的方式。)
这段代码有什么问题? 谢谢
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();
}
答案 0 :(得分:2)
您的代码实际上是正确的,但会查看Sampling theorem。
简而言之:您必须将采样率设置为高于2 * max_frequency。因此设置sampleRate = 44000
,你应该听到更高的频率。