Work on music, midi, and seq interfaces.
[cantaveria.git] / audio.c
blob2cb960f77efe452eb767c64d33e8a83fae24c5e4
1 /*
2 Cantaveria - action adventure platform game
3 Copyright (C) 2009 2010 Evan Rinehart
5 This program is free software; you can redistribute it and/or
6 modify it under the terms of the GNU General Public License
7 as published by the Free Software Foundation; either version 2
8 of the License, or (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to
18 The Free Software Foundation, Inc.
19 51 Franklin Street, Fifth Floor
20 Boston, MA 02110-1301, USA
23 #include <stdlib.h>
25 #include <SDL/SDL.h>
27 #include <org.h>
28 #include <synth.h>
29 #include <util.h>
30 #include <audio.h>
32 float* lout;
33 float* rout;
35 void audio_callback(void *userdata, Uint8 *stream, int bytes){
36 int i, j;
37 Sint16* out = (Sint16*)stream;
38 int buflen = bytes / 2; /* Sint16 = 2 bytes */
39 int samples = buflen / 2; /* 2 channels */
41 synth_generate(lout, rout, samples);
43 for(i=0, j=0; i<samples; i++){
44 out[j] = (Sint16)(lout[i]*32767); j++;
45 out[j] = (Sint16)(rout[i]*32767); j++;
51 char* sample_format_str(int format){
52 switch(format){
53 case AUDIO_S16: return "signed 16-bit LE";
54 case AUDIO_U16: return "unsigned 16-bit LE";
55 case AUDIO_S16MSB: return "signed 16-bit BE";
56 case AUDIO_U16MSB: return "unsigned 16-bit BE";
57 case AUDIO_S8: return "signed 8-bit";
58 case AUDIO_U8: return "unsigned 8-bit";
59 default: return "unknown";
63 void audio_init(){
64 SDL_AudioSpec want;
65 SDL_AudioSpec got;
68 want.freq = SAMPLE_RATE;
69 want.format = AUDIO_S16;
70 want.channels = 2;
71 want.samples = BUFFER_SIZE;
72 want.callback = audio_callback;
75 if(SDL_OpenAudio(&want, &got)<0){
76 report_error("sdl: cannot open audio (%s)\n", SDL_GetError());
77 exit(-1);
80 printf("audio:\n");
81 printf(" sample rate: %d\n", got.freq);
82 printf(" channels: %d\n", got.channels);
83 printf(" samples: %d\n", got.samples);
84 printf(" format: %s\n", sample_format_str(got.format));
86 if(got.format != AUDIO_S16){
87 printf(" WARNING: audio format not AUDIO_S16 :(\n");
88 SDL_CloseAudio();
89 printf(" *no sound*\n");
90 return;
92 lout = xmalloc(got.samples*sizeof(float));
93 rout = xmalloc(got.samples*sizeof(float));
94 memset(lout, 0, got.samples*sizeof(float));
95 memset(rout, 0, got.samples*sizeof(float));
97 org_init();
98 synth_init();
100 printf(" sound on\n");
101 SDL_PauseAudio(0);
106 void audio_quit(){
107 SDL_CloseAudio();
108 free(lout);
109 free(rout);
114 void audio_lock(){
115 SDL_LockAudio();
118 void audio_unlock(){
119 SDL_UnlockAudio();