• Advertisement
Sign in to follow this  

C++ Generating a pitch for a wav file

This topic is 3317 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi, I want to create a wav file that plays a tone. I understand how to set up the header but my question is what short values would i fill the array with to create a tone

Share this post


Link to post
Share on other sites
Advertisement
If you want a simple tone you can use a sine wave.

The size of radians increment steps on sin() depend on the frequency of output tone and the sampling defined in the header of wave file.

If you must write the values as integer shorts (16-bit) you must offset the sin value by 0.5 and add 0.5 the mulipty by 65535 like this:


unsigned short FloatToShort(float n)
{
return (unsigned short)((n * 0.5f + 0.5f) * 65535.0f);
}



Share this post


Link to post
Share on other sites
Once you know what sound waves look like, and understand that the values in a WAV file are basically just data for plotting the sound wave (each 16-bit value represents the relative height of the wave at that point, with however many equally spaced points per second), this is quite simple.

A sine wave produces a "pure" tone. This is not very aesthetically pleasing. You might want to mess around with a few different possible shapes. The easiest to produce is a square wave - just output X many 32767 values, followed by X many -32767 values, where 2X samples is the period of the desired tone.

Long period = low frequency (pitch). Short period (switching every other value would give the shortest possible period) = high frequency. Notes of overly low or high frequency may be inaudible.

A standard note for tuning is "A 440" - a 440 Hz tone. WAV data normally is written for a sampling frequency of either 22kHz or 44kHz, so correspondingly, a period of either 50 or 100 samples gives the desired tone (and thus you write 25 or 50 high values, followed by the same number of low values). Since the sampling frequency is 22kHz or 44kHz, 22,000 or 44,000 samples represent one second of sound.

You might also try Google's first result for audio synthesis tutorial.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement