我在生成具有特定频率的声音时遇到了一些麻烦。我已经设置了我的应用程序,因此您可以在搜索栏上来回滑动以选择特定频率,然后应用程序应使用该频率来生成音调。
我目前的音调很好,但它与您设置的频率完全不同。(而且我知道问题不在于将值从搜索栏传递到“音调生成过程”,所以它一定是我生成音调的方式。)
这段代码有什么问题?谢谢
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();
}