生成频率音时,我发现Playing an arbitrary tone with Android很有帮助。现在,我希望在播放声音时改变频率。
我将genTone修改为与此类似:
private void genTone(double startFreq, double endFreq, int dur) {
int numSamples = dur * sampleRate;
sample = new double[numSamples];
double currentFreq = 0, numerator;
for (int i = 0; i < numSamples; ++i) {
numerator = (double) i / (double) numSamples;
currentFreq = startFreq + (numerator * (endFreq - startFreq));
if ((i % 1000) == 0) {
Log.e("Current Freq:", String.format("Freq is: %f at loop %d of %d", currentFreq, i, numSamples));
}
sample[i] = Math.sin(2 * Math.PI * i / (sampleRate / currentFreq));
}
convertToPCM(numSamples);
}
private void convertToPCM(int numSamples) {
// convert to 16 bit pcm sound array
// assumes the sample buffer is normalised.
int idx = 0;
generatedSnd = new byte[2 * numSamples];
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);
}
}
日志显示似乎是currentFreq的正确值,但是,当听到声音时,扫描速度会过高且过快。例如,如果我从400hz开始并转到800hz,则示波器显示它实际上是同时从400hz变为1200z。
我不确定自己在做什么错,有人可以帮忙吗?
最佳答案
改变采样率对示波器测得的频率有什么影响?如果可能,我会尝试将采样率提高到更高的值,因为采样率越高,生成的信号越准确。
无论如何,如果这没有帮助,请从以下公式调整公式:
currentFreq = startFreq +(分子*(endFreq-startFreq));
至:
currentFreq = startFreq +(分子*(endFreq-startFreq)) / 2 ;
并告诉我们您信号变化的新测量间隔。
祝好运。