我已经实现了一个频率发生器,它将同时产生六个频率。它运作良好,但是当我调高手机音量(可能高达 50% 或更低,取决于手机)时,声音会破裂。我不知道为什么电话音量会导致这个问题......以下是我如何生成频率以及如何播放声音的部分代码。
private static double sampleRate = 44100;
private double freqOfTone; // hz
private int numSamples;
private double sample[];
public byte generatedSnd[];
private AudioTrack audioTrack;
public FrequencyGenerator(double freq, int soundInterval, int muteInterval) {
this.freq = freq;
this.soundInterval = soundInterval;
this.muteInterval = muteInterval;
this.freqOfTone = freq;
this.numSamples = (int) (sampleRate/1000*soundInterval);
sample = new double[this.numSamples];
generatedSnd = new byte[2*this.numSamples];
audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC,
(int) sampleRate, AudioFormat.CHANNEL_OUT_DEFAULT,
AudioFormat.ENCODING_PCM_16BIT, generatedSnd.length,
AudioTrack.MODE_STATIC);
}
void genTone() {
// fill out the array
for (int i = 0; i < numSamples; ++i) {
//sine wave
sample[i] = Math.sin(2 * Math.PI * i / (double)(sampleRate/freqOfTone));
}
// 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);
}
}
synchronized void makeSound() {
try {
audioTrack.write(generatedSnd, 0, generatedSnd.length);
switch (audioTrack.getPlayState()) {
case AudioTrack.PLAYSTATE_PAUSED:
audioTrack.stop();
audioTrack.reloadStaticData();
audioTrack.setLoopPoints(0, generatedSnd.length/4, -1);
audioTrack.play();
break;
case AudioTrack.PLAYSTATE_PLAYING:
audioTrack.stop();
audioTrack.reloadStaticData();
audioTrack.setLoopPoints(0, generatedSnd.length/4, -1);
audioTrack.play();
break;
case AudioTrack.PLAYSTATE_STOPPED:
audioTrack.reloadStaticData();
audioTrack.setLoopPoints(0, generatedSnd.length/4, -1);
audioTrack.play();
break;
}
} catch(IllegalStateException e) {
e.printStackTrace();
}
}
另一个使用频率生成器的类
public static FrequencyGenerator fg[] = new FrequencyGenerator[6];
void genSixFrequency() {
for(int i=0;i<6;i++) {
fg[i] = new FrequencyGenerator(i*1060 , sound, mute);
fg[i].genTone();
}
}
public void makeSixSound() {
for(int i=0;i<6;i++) {
fg[i].makeSound();
}
}
我会调用 makeSixSound() 来发出声音。然后当我调高音量时就会出现问题。有人知道这个问题吗?提前致谢。