- Download demo-25.7 KB
- Download source-33.1 KB
Introduction
This article demonstrates how to generate a quasi-infinite number of sounds using math formulas. Also, a sample program is provided to allow you to do experimentation by your own. have great times!
Background
A sound is basically a sine wave traveling in the air. it is characterized by a power and a frequency. the power determines the sound loudness and the frequency determines its pitch. if you are not familiar with this phenomenon, I propose you to start the sample program right now!
Sound frequency
First, try some variant of "sin (x * t)", beginning with X equal to 20 and increasing it progressively by step of 20. in that expression, "X" represents the frequency in Hertz and "T" is the time variable, varying from 0 to 2PI RAD in one second. maybe with x = 20 you will hear nothing. if this is the case, don't get mad, it's just that your speakers can't handle a so low frequency. (By the way, this is a good method to test your speakers 'quality .) for reference, humans generally can hear sine waves between 30Hz to 20000Hz.
Sampling Rate
In the digital world, sampling rate is the number of sound snapshots (called samples) that are used to generate a sine wave in the analog world. hence, higher is the sampling rate, better will be the sound fidelity. there is a fundamental theorem called the nyquest theorem that states that the sampling rate must be at least twice the highest analog frequency in order to accurately represent the Ori Ginal sound. in other words, if you want to hear a 1000Hz sine wave, the sampling rate must be at least 2000Hz. knowing that humans can hear sine waves up to 22000Hz, it's the reason behind the CD quality record sampling rate of 44100Hz (but of course, this not optimal; professional equipments use sampling rate of 48000Hz and higher ). sound samples are represented with bits, typically 8 or 16 bits Per sample. That value determines the minimum and the maximum value that a sound sample can take. if you bust these limits, you will hear distorted sounds (here are those alien sounds !). You can experiment this by adding a second sine wave to the preceding test and putting the volume all way up.
Adding two sounds
At first, it may be confusing, but you add sounds simply by using the "+" Operator! No fancy mathematics here. if you want to play two sine waves simultaneously, you just add their sin values like this: resultingsound (t) = sin (x * t) + sin (y * t ), where X and Y are sound frequencies.
Basic sine shape and other sound-Generating Functions
The general sine wave shape is "amplitude * sin (frequency * (t + delay ))". math formulas are evaluated using the math parser shown in this article. so, basic functions like sin, cos, tan, Min, and Max come with the sample application, but it is also very easy to define your own functions (read the above article for more details ).
The sample program
The sample program is a little lab that allows you to test varous sound shapes using math formulas. to be more convenient, you can break your sounds in up to three independent sound shapes instead of putting them all together in a very large formula. this also means that you can "mix" as your sounds as you want by using the "+" Operator and scaling them to avoid busting the amplitude limits.
Again for the sake of usability, you can use variables to lighten your sound shape formulas. variables are named x, y, and z. you can use another special "system" variable named "T ". this variable is the time counter in radians.
In the bottom of the sample application screen is shown the resulting wave. you can see the effect of each sound shape individually by activating and deactivating them. you can also check if the resulting sound is too between and thus generating distortion.
One last thing: the compute time indicator. evaluating thousands of expressions per second can be very demanding for your computer. if your computer is too slow, the sound will not be played correctly. in this case, the time indicator will display a "warning" message. you can diminish the number of evaluations per second by decreasing the sampling rate or switching your math formula's complexity.
A look at the code
There are three fundamental things here: playing sounds, evaluating math formulas, and mixing sounds.
To play sound, I use directsound. the Mechanism is simple: create a sound buffer and a few notification events that will tell you when it is time to compute the next thousand sound samples and update the sound buffer. this code is executed inCSoundGeneratorDlg::OnInitDialog()
Method.
Next, when you need to compute the sound samples, the first thing to do is to evaluate variable values that will be used by sound shape formulas. after that, you evaluate sound shape formulas and add their values by scaling them according to the corresponding volume. finally, you increment the time variablet
And redo the variables and sound shapes evaluation until enough sound samples will have been computed. The following code snippet shows how this is implemented:
for( int s=0; s < m_soundPlayerEventNbSamples; s++ ){ sample = 0; for( int t=0; t < m_nbVars; t++ ) { m_pUserVar[t] = m_pVarExpr[t].evaluate(); } for( t=0; t < m_nbShapes; t++ ) { if( m_pShapeActive[t] ) { // volume scaling sample += m_pShapeExpr[t].evaluate() * m_pShapeVolume[t]; } } // rescaling to the sample range m_pSamples[s] = sample* m_sampleScaleVal; m_t+=m_tStep;}
There are some details to be aware. first, sine function value ranges from-1 to 1, so it must be rescaled to cover the entire sample range that is, in 16 bits,-2 ^ 15 to 2 ^ 15. with 8 bits sound samples, this scale value wocould be different (I. E ., -2 ^ 7 to 2 ^ 7 ). another thing to note is how the time is computed. sincesin(x)
Function takes radian value as input, the time variable must grow by exactly 2 * PI in one second in order to generate a 1Hz sine wave. Ifsin(x)
Function input value wocould have been in degrees instead of radians, then the time variable wocould grow by 360 (degrees) each second. The variablem_step
Is the time increment per sample.
Performance issue
Because generating high quality sound in real-time is very CPU intensive, performance is a major issue. I ran the code profiler and found that the most demaning computation was the math expression evaluations. so, I optimized the math parser and succeeded to save some precious milliseconds. maybe you will notice that the math parser uses a recursive algorithm to evaluate expression, and will wonder if this is a good idea since performance is an issue. I asked me the same question, and I tried a non-recursive algorithm. the result was that while this solution ran faster in debug mode (twice as fast), in release mode, the recursive solution ran faster (a couple of milliseconds faster ). so, I concluded that the compiler cocould do a lot of optimizations with a recursive algorithm and hence, I put it in the final software version.
The morale of this tale is that before doing performance optimization, always use a profiler to find where are the performance bottlenecks, and always use a profiler to validate that your changes actually increased performance.
History
June 17-first draft.
License
This article has no explicit license attached to it but may contain in usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.
A list of licenses authors may to use can be found here