Search code examples
javaaudiojavasound

How to find a note's length in frames, bytes, and ints from its length in milliseconds


I need to make a function in Java that adds a note of a certain frequency and length to audio. I have the frequency as a double, and the note length in milliseconds.

Full Function Description:

This method takes one AudioInputStream and adds the sound of a certain pure frequency to the FRONT of it, lasting a certain length of time. So the method takes two additional parameters: frequency and noteLengthInMilliseconds. The amplitude of the additional sound should be 64*256.

However, I need to find the note's length in Frames, as well as in Bytes and Ints.

Also, any advice on how to create the note as a data array of samples (am using java.sound.sampled package) would be helpful.

FRAME & SAMPLE RATE: 44100.0hz
ENCODING: PCM_SIGNED


Solution

  • Since your frame rate and sample rate are identical, let's assume you're referring to PCM frames. A PCM frame is one sample per channel. If you only have one audio channel, at 16 bits per sample, you get one frame every two bytes. If you have stereo audio at 16 bits per sample, you get one frame every four bytes.

    To figure out the length, take the sample rate and divide it out. If I have a sample rate of 44.1 kHz and I want a note to last for a half second:

    44,100 * 0.5 = 22,050 samples (22,050 frames)
    

    From there if you know that the audio is 16 bits, and there is only one channel:

    22,050 * 2 (bytes per channel) * 1 (channels) = 44,100 bytes