-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathdemo_stereo.c
107 lines (88 loc) · 2.37 KB
/
demo_stereo.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
/* Generates left and right channels and interleaves them together */
#include "blip_buf.h"
#include "wave_writer.h"
#include <stdlib.h>
enum { sample_rate = 44100 };
static const double clock_rate = (double) sample_rate * blip_max_ratio;
/* Delta buffers for left and right channels */
static blip_buffer_t* blips [2];
typedef struct wave_t
{
blip_buffer_t* blip; /* delta buffer to output to */
double frequency;
double volume;
int phase;
int time;
int amp;
} wave_t;
static wave_t waves [2];
static void run_wave( wave_t* w, int clocks )
{
int period = (int) (clock_rate / w->frequency / 2 + 0.5);
int volume = (int) (w->volume * 65536 / 2 + 0.5);
for ( ; w->time < clocks; w->time += period )
{
int delta = w->phase * volume - w->amp;
w->amp += delta;
blip_add_delta( w->blip, w->time, delta );
w->phase = -w->phase;
}
w->time -= clocks;
}
static void gen_samples( short out [], int samples )
{
int pairs = samples / 2; /* number of stereo sample pairs */
int clocks = blip_clocks_needed( blips [0], pairs );
int i;
run_wave( &waves [0], clocks );
run_wave( &waves [1], clocks );
/* Generate left and right channels, interleaved into out */
for ( i = 0; i < 2; ++i )
{
blip_end_frame( blips [i], clocks );
blip_read_samples( blips [i], out + i, pairs, 1 );
}
}
static void init_sound( void )
{
/* Create left and right delta buffers */
int i;
for ( i = 0; i < 2; ++i )
{
blips [i] = blip_new( sample_rate / 10 );
if ( blips [i] == NULL )
exit( EXIT_FAILURE ); /* out of memory */
blip_set_rates( blips [i], clock_rate, sample_rate );
}
}
int main( void )
{
init_sound();
waves [0].blip = blips [0];
waves [0].phase = 1;
waves [0].volume = 0.0;
waves [0].frequency = 16000;
waves [1].blip = blips [1];
waves [1].phase = 1;
waves [1].volume = 0.5;
waves [1].frequency = 1000;
wave_open( sample_rate, "out.wav" );
wave_enable_stereo();
while ( wave_sample_count() < 2 * sample_rate * 2 )
{
enum { samples = 2048 };
short temp [samples];
gen_samples( temp, samples );
wave_write( temp, samples );
/* Slowly increase volume and lower pitch */
waves [0].volume += 0.005;
waves [0].frequency *= 0.950;
/* Slowly decrease volume and raise pitch */
waves [1].volume -= 0.002;
waves [1].frequency *= 1.010;
}
wave_close();
blip_delete( blips [0] );
blip_delete( blips [1] );
return 0;
}