LAK132

SDL+TCC

Jun 1st, 2019
747
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.68 KB | None | 0 0
  1. #!/usr/bin/tcc -run -I/usr/include/SDL2 -lSDL2
  2. #include <math.h>
  3. #include <stdlib.h>
  4. #include <unistd.h>
  5. #define SDL_DISABLE_IMMINTRIN_H
  6. #include <SDL.h>
  7. #include <SDL_audio.h>
  8.  
  9. int AMPLITUDE = 28000;
  10. int SAMPLE_RATE = 44100;
  11.  
  12. void audio_callback(void *user_data, Uint8 *raw_buffer, int bytes)
  13. {
  14.     Sint16 *buffer = (Sint16*)raw_buffer;
  15.     int length = bytes / 2;
  16.     int *sample_nr = (int*)user_data;
  17.     if (sample_nr == NULL)
  18.         return;
  19.  
  20.     for (int i = 0; i < length; ++i, ++*sample_nr)
  21.     {
  22.         double time = (double)*sample_nr / (double)SAMPLE_RATE;
  23.         buffer[i] = (Sint16)(AMPLITUDE * sin(2.0f * M_PI * 441.0f * time));
  24.     }
  25. }
  26.  
  27. int main(int argc, char *argv[])
  28. {
  29.     int c;
  30.     while ((c = getopt(argc, argv, "A:S:")) != -1)
  31.     {
  32.         switch (c)
  33.         {
  34.             case 'A': AMPLITUDE = atoi(optarg); break;
  35.             case 'S': SAMPLE_RATE = atoi(optarg); break;
  36.             default: break;
  37.         }
  38.     }
  39.  
  40.     if (SDL_Init(SDL_INIT_AUDIO) != 0)
  41.         SDL_Log("Failed to initialize SDL: %s", SDL_GetError());
  42.  
  43.     int sample_nr = 0;
  44.  
  45.     SDL_AudioSpec want;
  46.     want.freq = SAMPLE_RATE;
  47.     want.format = AUDIO_S16SYS;
  48.     want.channels = 1;
  49.     want.samples = 2048;
  50.     want.callback = audio_callback;
  51.     want.userdata = &sample_nr;
  52.  
  53.     SDL_AudioSpec have;
  54.     if (SDL_OpenAudio(&want, &have) != 0)
  55.         SDL_LogError(SDL_LOG_CATEGORY_AUDIO, "Failed to open audio: %s", SDL_GetError());
  56.     if (want.format != have.format)
  57.         SDL_LogError(SDL_LOG_CATEGORY_AUDIO, "Failed to get the desired AudioSpec");
  58.  
  59.     SDL_PauseAudio(0);
  60.     SDL_Delay(1000);
  61.     SDL_PauseAudio(1);
  62.  
  63.     SDL_CloseAudio();
  64.  
  65.     return 0;
  66. }
Advertisement
Add Comment
Please, Sign In to add comment