2

I'm trying to build a frequency generator in java, but i'm having some trouble. For some reason I'm getting exactly what I want on my headphone speaker, but when I try the same code on my macbook pro 13" speaker it just doesn't work. The problem only occurs for high frequencies (i'm trying between 19kHz to 20kHz). For lower frequencies (such as 10kHz) I get the right results.

I'm using a sample rate of 44100.

Here is the code to play the produced sine frequency:

AudioFormat af = new AudioFormat(sampleRate, 16, 1, true, true );
DataLine.Info info = new DataLine.Info ( SourceDataLine.class, af );
SourceDataLine source = (SourceDataLine) AudioSystem.getLine( info );
source.open(af);
source.start();

source.write( buf, 0, buf.length );
source.drain();
source.stop();
source.close();

Here is how I'm generating the buffer:

    public void play(float seconds, int sampleRate, double frequency){

        for (int i = 0; i < numSamples; ++i) {
            sample[i] = Math.sin((2 * Math.PI * i / (sampleRate/frequency)));
        }
        for (final double dVal : sample) {
            final short val = (short) ((dVal * 32767));                

            buf[pos++] = (byte) ((val & 0xff00) >>> 8);
            buf[pos++] = (byte) (val & 0x00ff);

        }
    }

[UPDATE]

The problem starts at 18kHz. Right now the best explanation is:

It's possible there's some fairly agressive anti-aliasing filters in the mac, and that the dog park software app isn't using PCM buffering to generate the sounds, like you are. I would try a higher sampling frequency if possible. Blockquote -(comment made by Robert) But we are not 100% sure if this is precise.

One alternative solution is to plug an external speaker (make sure the computer volume is set to maximum, and regulate it on the speaker).

4

0 回答 0