Question

I'm just making a tone generator and I was able to find code that makes a sine wave of a specified frequency:

private void genTone(){
    // fill out the array
    for (int i = 0; i < numSamples; ++i) {
        sample[i] = Math.sin(2 * Math.PI * i / (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);

    }
}

private void playSound(){
    final AudioTrack audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC,
            sampleRate, AudioFormat.CHANNEL_CONFIGURATION_MONO,
            AudioFormat.ENCODING_PCM_16BIT, generatedSnd.length,
            AudioTrack.MODE_STATIC);
    audioTrack.write(generatedSnd, 0, generatedSnd.length);
    audioTrack.play();
}

And I know from Wikipedia, the formula for a sawtooth tone is:

x(t) = t - floor(t);

How would I implement that into the genTone function? Really the thing that keeps me from figuring this out on my own is how frequency can be related to period (period doesn't involve time like frequency does unless I'm missing something. I'm not too great with sound science.)

Thank you for any help in advance!

Was it helpful?

Solution

Period= 1/frequency, if that helps you figure it out.

You can substitute this for your sample generation expression:

sample[i]= 2*(i%(sampleRate/freqOfTone))/(sampleRate/freqOfTone)-1;

Here is an example of how it works. Code is adapted from here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top