-
Notifications
You must be signed in to change notification settings - Fork 0
/
sound.c
142 lines (85 loc) · 2.26 KB
/
sound.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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
#include <SDL/SDL.h>
static Uint8 *audio_buffer;
static Uint32 audio_len=0;
static Uint8 *audio_pos;
SDL_AudioSpec wanted;
int audio_pointer=0;
int audio_read=0;
int buffer_size=4096*32;
void soundRun()
{
}
void fill_audio(void *udata, Uint8 *stream, int len)
{
/* Only play if we have data left */
if (( audio_len < 0 )){
// audio_read=0;
return;
}
/* Mix as much data as possible */
len = ( len > audio_len ? audio_len : len );
// printf("audiopointer %d audioread %d audio_len %d len %d\n",audio_pointer,audio_read,audio_len,len);
// SDL_MixAudio(stream, audio_buffer, len, SDL_MIX_MAXVOLUME);
/*protect against underruns*/
if((audio_read+len>=audio_pointer)&&(audio_read<audio_pointer))
{
SDL_PauseAudio(1);
audio_pointer=0;
audio_read=0;
printf("INFO: audio underrun!\n");
return;
}
memcpy(stream,audio_buffer+audio_read,len);
audio_read+=len;
if(audio_read>=buffer_size)
{
audio_read=0;
}
//audio_buffer-=len;
}
int soundInit()
{
if((SDL_InitSubSystem( SDL_INIT_AUDIO )) < 0 )
{
printf("ERROR: can't init sound\n");
return 0;
}
printf("INFO: sound init success\n");
/* Set the audio format */
wanted.freq = 22050;
wanted.format = AUDIO_S16LSB;
wanted.channels = 2; /* 1 = mono, 2 = stereo */
wanted.samples = 512; /* Good low-latency value for callback */
wanted.callback = fill_audio;
wanted.userdata = NULL;
/* Open the audio device, forcing the desired format */
if ( SDL_OpenAudio(&wanted, NULL) < 0 )
printf("Couldn't open audio: %s\n", SDL_GetError());
audio_buffer=(Uint8 *)malloc(buffer_size);
memset(audio_buffer,0,buffer_size);
return 1;
}
void soundFillBuffer(unsigned int dspLoop)
{
// if(audio_len<131040){
if(audio_pointer<buffer_size){
memcpy(audio_buffer+audio_pointer,&dspLoop,4);
audio_pointer+=2;
}else{
audio_pointer=0;
// audio_read=0;
}
if(audio_pointer>buffer_size*3/4)
SDL_PauseAudio(0);
// printf("audio_pointer %d\n",audio_pointer);
if(audio_pointer>=audio_read)
audio_len=(audio_pointer-audio_read);
else
audio_len=((buffer_size-audio_read));
// if(audio_len<500)audio_len=((buffer_size-audio_read*2)/2);
// printf("audiopointer %d audioread %d\n",audio_pointer*32,audio_read);
}
void soundClose()
{
SDL_CloseAudio();
}