1 | # /*
|
---|
2 | g++ "$0" "$@" -o sdlaudio `sdl-config --cflags --libs`
|
---|
3 | exit
|
---|
4 | */
|
---|
5 |
|
---|
6 | #include "SDL.h"
|
---|
7 | #include "SDL_audio.h"
|
---|
8 | #include <stdlib.h>
|
---|
9 | #include <math.h>
|
---|
10 |
|
---|
11 | SDL_Surface *screen;
|
---|
12 | SDL_AudioSpec spec;
|
---|
13 | Uint32 sound_len;
|
---|
14 | Uint8 *sound_buffer;
|
---|
15 | int sound_pos = 0;
|
---|
16 | int counter;
|
---|
17 |
|
---|
18 | //Do all the init stuff
|
---|
19 | void init_sdl (void)
|
---|
20 | {
|
---|
21 | if (SDL_Init (SDL_INIT_VIDEO|SDL_INIT_AUDIO) < 0)
|
---|
22 | exit (-1);
|
---|
23 | atexit (SDL_Quit);
|
---|
24 | screen = SDL_SetVideoMode (640, 480, 16, SDL_HWSURFACE);
|
---|
25 | if (screen == NULL)
|
---|
26 | exit (-1);
|
---|
27 | }
|
---|
28 |
|
---|
29 | //Creates the sine wave. To supress ripple, the wave runs continuously by using an incemental counter
|
---|
30 | void Callback (void *userdata, Uint8 *stream, int len)
|
---|
31 | {
|
---|
32 | double pi = 3.1415;
|
---|
33 | Uint8 *waveptr;
|
---|
34 | double Hz=50;
|
---|
35 | double L = 512;
|
---|
36 | double A = 100;
|
---|
37 | double SR = 44100;
|
---|
38 | double F=2*pi*Hz/SR;
|
---|
39 |
|
---|
40 | for (int z = 0; z< 512 ; z++)
|
---|
41 | {
|
---|
42 | counter++;
|
---|
43 | sound_buffer[z] = (Uint8) A*sin(F*(double)counter);
|
---|
44 | }
|
---|
45 |
|
---|
46 | //Do the sound loop...
|
---|
47 | if (sound_pos + len > sound_len)
|
---|
48 | {
|
---|
49 | sound_pos=0;
|
---|
50 | }
|
---|
51 |
|
---|
52 | waveptr = sound_buffer + sound_pos;
|
---|
53 | SDL_MixAudio(stream, waveptr, len, SDL_MIX_MAXVOLUME);
|
---|
54 |
|
---|
55 | //stream = waveptr; //Replacing the mixer gives nothing but silence...!?!
|
---|
56 |
|
---|
57 | sound_pos += len;
|
---|
58 | }
|
---|
59 |
|
---|
60 | void play (void)
|
---|
61 | {
|
---|
62 | sound_buffer = new Uint8[512];
|
---|
63 | sound_len= 512;
|
---|
64 | spec.freq = 44100;
|
---|
65 | spec.format = AUDIO_S16SYS;
|
---|
66 | spec.channels = 1;
|
---|
67 | spec.silence = 0;
|
---|
68 | spec.samples = 512;
|
---|
69 | spec.padding = 0;
|
---|
70 | spec.size = 0;
|
---|
71 | spec.userdata = 0;
|
---|
72 |
|
---|
73 | spec.callback = Callback;
|
---|
74 | if (SDL_OpenAudio (&spec, NULL) < 0)
|
---|
75 | {
|
---|
76 | printf ("Kann audio nicht öffnen: %s\n", SDL_GetError ());
|
---|
77 | exit (-1);
|
---|
78 | }
|
---|
79 | SDL_PauseAudio (0);
|
---|
80 | }
|
---|
81 |
|
---|
82 | int main()
|
---|
83 | {
|
---|
84 | init_sdl ();
|
---|
85 | play ();
|
---|
86 | SDL_Delay (5000);
|
---|
87 | return 0;
|
---|
88 |
|
---|
89 | }
|
---|
90 |
|
---|