KobeSystem
KobeSystem

Reputation: 61

Java playing wrong sound frequency

I am writing a java sound application that transitions linearly from one frequency to another.

When I input a constant frequency (aka the first and last frequency are the same), the correct frequency is played.

However, whenever the difference between the two frequencies is greater than zero, the frequency played starts at the correct value, but increments at double the rate, and ends up at double the difference. (e.g. I input 500 and 1000; the frequency starts at 500 and ends at 1500).

I originally thought that I was simply incorrectly incrementing the frequency, but when I print the frequency values, it prints the values I had intended (e.g. I input 500 and 1000; the printed output starts at 500 and ends at 1000).

I checked the value of the audible frequency by recording the output sound and looking at its frequency on a frequency spectrogram. Here is the relevant simplified part of my code:

import java.lang.Math;
import javax.sound.sampled.*;

public class MainSpeech {

    public static void main(String[] args) throws LineUnavailableException {

        double freq; //  frequency in Hz
        int volume = 30;
        int time = 1; // in seconds
        float sampleRate = 8000.0f; // in Hz
        int numSamples = (int)(sampleRate * time); // # of samples within given time
        byte stream[] = new byte[(int)(sampleRate*1)]; // waveform values

        freq = 700;
        for (int i = 0; i < numSamples; i++) {
            freq += 0.1;
            stream[i] = (byte) (Math.sin(2*Math.PI*i*freq/sampleRate)*volume);
        }

        AudioFormat af = new AudioFormat(sampleRate, 8, 1, true, false);
        SourceDataLine sdl = AudioSystem.getSourceDataLine(af);
        sdl.open(af);
        sdl.start();
        sdl.write(stream, 0, stream.length); // play sound
        sdl.drain();
        sdl.close();
    }
}

In this simplified snippet, the frequency should start at 700, and increase eight thousand times by 0.1, ending at a frequency of 1500, which a printout correctly displays. However the audible frequency actually ends at 2300.

Upvotes: 1

Views: 953

Answers (1)

Gangnus
Gangnus

Reputation: 24464

You have an error here:

2*Math.PI*i*freq/sampleRate

Use here i or freq, but not both of them. What you have is not a linear change of frequency, but quadratical. If you want it to behave as you describe below, use

2*Math.PI*freq/sampleRate

Upvotes: 3

Related Questions