Generate Sawtooth Tone in Java/Android

ぐ巨炮叔叔 提交于 2019-12-25 01:45:22

问题


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!


回答1:


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



来源:https://stackoverflow.com/questions/17604968/generate-sawtooth-tone-in-java-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!