2 * OpenAL Audio Stream Example
4 * Copyright (c) 2011 by Chris Robinson <chris.kcat@gmail.com>
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25 /* This file contains a relatively simple streaming audio player. */
33 #include <SDL_sound.h>
39 #include "common/alhelpers.h"
42 #ifndef SDL_AUDIO_MASK_BITSIZE
43 #define SDL_AUDIO_MASK_BITSIZE (0xFF)
45 #ifndef SDL_AUDIO_BITSIZE
46 #define SDL_AUDIO_BITSIZE(x) (x & SDL_AUDIO_MASK_BITSIZE)
49 /* Define the number of buffers and buffer size (in milliseconds) to use. 4
50 * buffers with 200ms each gives a nice per-chunk size, and lets the queue last
51 * for almost one second. */
53 #define BUFFER_TIME_MS 200
55 typedef struct StreamPlayer
{
56 /* These are the buffers and source to play out through OpenAL with */
57 ALuint buffers
[NUM_BUFFERS
];
60 /* Handle for the audio file */
63 /* The format of the output stream */
68 static StreamPlayer
*NewPlayer(void);
69 static void DeletePlayer(StreamPlayer
*player
);
70 static int OpenPlayerFile(StreamPlayer
*player
, const char *filename
);
71 static void ClosePlayerFile(StreamPlayer
*player
);
72 static int StartPlayer(StreamPlayer
*player
);
73 static int UpdatePlayer(StreamPlayer
*player
);
75 /* Creates a new player object, and allocates the needed OpenAL source and
76 * buffer objects. Error checking is simplified for the purposes of this
77 * example, and will cause an abort if needed. */
78 static StreamPlayer
*NewPlayer(void)
82 player
= calloc(1, sizeof(*player
));
83 assert(player
!= NULL
);
85 /* Generate the buffers and source */
86 alGenBuffers(NUM_BUFFERS
, player
->buffers
);
87 assert(alGetError() == AL_NO_ERROR
&& "Could not create buffers");
89 alGenSources(1, &player
->source
);
90 assert(alGetError() == AL_NO_ERROR
&& "Could not create source");
92 /* Set parameters so mono sources play out the front-center speaker and
93 * won't distance attenuate. */
94 alSource3i(player
->source
, AL_POSITION
, 0, 0, -1);
95 alSourcei(player
->source
, AL_SOURCE_RELATIVE
, AL_TRUE
);
96 alSourcei(player
->source
, AL_ROLLOFF_FACTOR
, 0);
97 assert(alGetError() == AL_NO_ERROR
&& "Could not set source parameters");
102 /* Destroys a player object, deleting the source and buffers. No error handling
103 * since these calls shouldn't fail with a properly-made player object. */
104 static void DeletePlayer(StreamPlayer
*player
)
106 ClosePlayerFile(player
);
108 alDeleteSources(1, &player
->source
);
109 alDeleteBuffers(NUM_BUFFERS
, player
->buffers
);
110 if(alGetError() != AL_NO_ERROR
)
111 fprintf(stderr
, "Failed to delete object IDs\n");
113 memset(player
, 0, sizeof(*player
));
118 /* Opens the first audio stream of the named file. If a file is already open,
119 * it will be closed first. */
120 static int OpenPlayerFile(StreamPlayer
*player
, const char *filename
)
124 ClosePlayerFile(player
);
126 /* Open the file and get the first stream from it */
127 player
->sample
= Sound_NewSampleFromFile(filename
, NULL
, 0);
130 fprintf(stderr
, "Could not open audio in %s\n", filename
);
134 /* Get the stream format, and figure out the OpenAL format */
135 if(player
->sample
->actual
.channels
== 1)
137 if(player
->sample
->actual
.format
== AUDIO_U8
)
138 player
->format
= AL_FORMAT_MONO8
;
139 else if(player
->sample
->actual
.format
== AUDIO_S16SYS
)
140 player
->format
= AL_FORMAT_MONO16
;
143 fprintf(stderr
, "Unsupported sample format: 0x%04x\n", player
->sample
->actual
.format
);
147 else if(player
->sample
->actual
.channels
== 2)
149 if(player
->sample
->actual
.format
== AUDIO_U8
)
150 player
->format
= AL_FORMAT_STEREO8
;
151 else if(player
->sample
->actual
.format
== AUDIO_S16SYS
)
152 player
->format
= AL_FORMAT_STEREO16
;
155 fprintf(stderr
, "Unsupported sample format: 0x%04x\n", player
->sample
->actual
.format
);
161 fprintf(stderr
, "Unsupported channel count: %d\n", player
->sample
->actual
.channels
);
164 player
->srate
= player
->sample
->actual
.rate
;
166 frame_size
= player
->sample
->actual
.channels
*
167 SDL_AUDIO_BITSIZE(player
->sample
->actual
.format
) / 8;
169 /* Set the buffer size, given the desired millisecond length. */
170 Sound_SetBufferSize(player
->sample
, (Uint32
)((Uint64
)player
->srate
*BUFFER_TIME_MS
/1000) *
177 Sound_FreeSample(player
->sample
);
178 player
->sample
= NULL
;
183 /* Closes the audio file stream */
184 static void ClosePlayerFile(StreamPlayer
*player
)
187 Sound_FreeSample(player
->sample
);
188 player
->sample
= NULL
;
192 /* Prebuffers some audio from the file, and starts playing the source */
193 static int StartPlayer(StreamPlayer
*player
)
197 /* Rewind the source position and clear the buffer queue */
198 alSourceRewind(player
->source
);
199 alSourcei(player
->source
, AL_BUFFER
, 0);
201 /* Fill the buffer queue */
202 for(i
= 0;i
< NUM_BUFFERS
;i
++)
204 /* Get some data to give it to the buffer */
205 Uint32 slen
= Sound_Decode(player
->sample
);
208 alBufferData(player
->buffers
[i
], player
->format
,
209 player
->sample
->buffer
, slen
, player
->srate
);
211 if(alGetError() != AL_NO_ERROR
)
213 fprintf(stderr
, "Error buffering for playback\n");
217 /* Now queue and start playback! */
218 alSourceQueueBuffers(player
->source
, i
, player
->buffers
);
219 alSourcePlay(player
->source
);
220 if(alGetError() != AL_NO_ERROR
)
222 fprintf(stderr
, "Error starting playback\n");
229 static int UpdatePlayer(StreamPlayer
*player
)
231 ALint processed
, state
;
233 /* Get relevant source info */
234 alGetSourcei(player
->source
, AL_SOURCE_STATE
, &state
);
235 alGetSourcei(player
->source
, AL_BUFFERS_PROCESSED
, &processed
);
236 if(alGetError() != AL_NO_ERROR
)
238 fprintf(stderr
, "Error checking source state\n");
242 /* Unqueue and handle each processed buffer */
248 alSourceUnqueueBuffers(player
->source
, 1, &bufid
);
251 if((player
->sample
->flags
&(SOUND_SAMPLEFLAG_EOF
|SOUND_SAMPLEFLAG_ERROR
)))
254 /* Read the next chunk of data, refill the buffer, and queue it
255 * back on the source */
256 slen
= Sound_Decode(player
->sample
);
259 alBufferData(bufid
, player
->format
, player
->sample
->buffer
, slen
,
261 alSourceQueueBuffers(player
->source
, 1, &bufid
);
263 if(alGetError() != AL_NO_ERROR
)
265 fprintf(stderr
, "Error buffering data\n");
270 /* Make sure the source hasn't underrun */
271 if(state
!= AL_PLAYING
&& state
!= AL_PAUSED
)
275 /* If no buffers are queued, playback is finished */
276 alGetSourcei(player
->source
, AL_BUFFERS_QUEUED
, &queued
);
280 alSourcePlay(player
->source
);
281 if(alGetError() != AL_NO_ERROR
)
283 fprintf(stderr
, "Error restarting playback\n");
292 int main(int argc
, char **argv
)
294 StreamPlayer
*player
;
297 /* Print out usage if no arguments were specified */
300 fprintf(stderr
, "Usage: %s [-device <name>] <filenames...>\n", argv
[0]);
305 if(InitAL(&argv
, &argc
) != 0)
310 player
= NewPlayer();
312 /* Play each file listed on the command line */
313 for(i
= 0;i
< argc
;i
++)
315 const char *namepart
;
317 if(!OpenPlayerFile(player
, argv
[i
]))
320 /* Get the name portion, without the path, for display. */
321 namepart
= strrchr(argv
[i
], '/');
322 if(namepart
|| (namepart
=strrchr(argv
[i
], '\\')))
327 printf("Playing: %s (%s, %dhz)\n", namepart
, FormatName(player
->format
),
331 if(!StartPlayer(player
))
333 ClosePlayerFile(player
);
337 while(UpdatePlayer(player
))
338 al_nssleep(10000000);
340 /* All done with this file. Close it and go to the next */
341 ClosePlayerFile(player
);
345 /* All files done. Delete the player, and close down SDL_sound and OpenAL */
346 DeletePlayer(player
);