7 This is a simple [C](c.md) program (using [float](float.md) for simplicity of demonstration) that creates basic vowel sounds using formant synthesis (run e.g. as `gcc -lm program.c && ./a.out | aplay`, 8000 Hz 8 bit audio is supposed):
13 double vowelParams[] = { // vocal tract shapes, can be found in literature
14 // formant1 formant2 width1 width2 amplitude1 amplitude2
15 850, 1650, 500, 500, 1, 0.2, // a
16 390, 2300, 500, 450, 1, 0.9, // e
17 240, 2500, 300, 500, 1, 0.5, // i
18 250, 600, 500, 400, 1, 0.9, // o
19 300, 400, 400, 400, 1, 1.0 // u
22 double tone(double t, double f) // tone of given frequency
24 return sin(f * t * 2 * M_PI);
27 /* simple linear ("triangle") function for modelling spectral shape
28 of one formant with given frequency location, width and amplitude */
29 double formant(double freq, double f, double w, double a)
31 double r = ((freq - f + w / 2) * 2 * a) / w;
36 return r > 1 ? 1 : (r < 0 ? 0 : r);
39 /* gives one sample of speech, takes two formants as input, fundamental
40 frequency and possible offset of both formants (can model "bigger/smaller
42 double speech(double t, double fundamental, double offset,
47 int harmonic = 1; // number of harmonic frequency
51 /* now generate harmonics (multiples of fundamental frequency) as the source,
52 and multiply them by the envelope given by formants (no need to deal with
53 multiplication of spectra; as we're constructing the result from basic
54 frequencies, we can simply multiply each one directly): */
57 double f = harmonic * fundamental;
58 double formant1 = formant(f,f1 + offset,w1,a1);
59 double formant2 = formant(f,f2 + offset,w2,a2);
61 // envelope = max(formant1,formant2)
62 r += (formant1 > formant2 ? formant1 : formant2) * 0.1 * tone(t,f);
64 if (f > 10000) // stop generating harmonics above 10000 Hz
70 return r > 1.0 ? 1.0 : (r < 0 ? 0 : r); // clamp between 0 and 1
75 for (int i = 0; i < 50000; ++i)
77 double t = ((double) i) / 8000.0;
78 double *vowel = vowelParams + ((i / 4000) % 5) * 6; // change vowels
81 speech(t,150,-100,vowel[0],vowel[1],vowel[2],vowel[3],vowel[4],vowel[5]));