summaryrefslogtreecommitdiff
path: root/audiotest.cpp
blob: f6b5a928e9d0cf224bef651d5d17dcf538e4c620 (plain)
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
//emcc -o test.html main.cpp -O2 -s USE_SDL=2

#include <stdlib.h>

#if defined(_MSC_VER)
#include "SDL.h"
#else
#include "SDL2/SDL.h"
#endif

#include <math.h>
#include <stdio.h>

#ifdef __EMSCRIPTEN__
#include "emscripten.h"
#endif



void audiomixer(void *userdata, Uint8 *stream, int len)
{
    int samples = len / 4;
    short *buf = (short*)stream;

    int i;
    for (i = 0; i < samples*2; i++)
    {
        buf[i] = i * 655;
    }
}

int sdlstatic_init(unsigned int aSamplerate, unsigned int aBuffer)
{
    SDL_AudioSpec as;
    as.freq = aSamplerate;
    as.format = AUDIO_S16;
    as.channels = 2;
    as.samples = aBuffer;
    as.callback = audiomixer;

    SDL_AudioSpec as2;
    if (SDL_OpenAudio(&as, &as2) < 0)
    {
        return -1;
    }

    SDL_PauseAudio(0);

    return 0;
}   

void mainloop()
{
    // Poll for events, and handle the ones we care about.
    SDL_Event event;
    while (SDL_PollEvent(&event)) 
    {
        switch (event.type) 
        {
        case SDL_KEYUP:
            // If escape is pressed, return (and thus, quit)
            switch (event.key.keysym.sym)
            {
            case SDLK_ESCAPE:
                {
                    exit(0);
                }
                break;
            }
            break;
        case SDL_QUIT:
            SDL_CloseAudio();
            exit(0);
        }
    }
}

int main(int argc, char *argv[])
{   
    printf("SDL INIT OK\n");
    if ( SDL_Init(SDL_INIT_EVERYTHING) < 0 ) 
    {
        fprintf(stderr, "Unable to init SDL: %s\n", SDL_GetError());
        exit(1);
    }   
    printf("SDL INIT OK\n");

    atexit(SDL_Quit);   

    sdlstatic_init(44100, 1024);

#ifdef __EMSCRIPTEN__
    emscripten_set_main_loop(mainloop, 60, 0);
#else
    while (1)
    {
        mainloop();
    }
#endif
    return 0;
}