Guest User

Untitled

a guest
Oct 10th, 2014
229
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.30 KB | None | 0 0
  1. #include <SDL2/SDL.h>
  2. #include <math.h>
  3.  
  4. #define PI 3.14159265358979323846
  5. #define BufferSizeInSamples 2048
  6. #define BytesPerSample 2 // 16 bit PCM
  7. #define BufferSizeInBytes (BufferSizeInSamples * BytesPerSample)
  8. #define SampleRate 44100 // Hz
  9. #define Frequence 1000 // Hz
  10. #define Volume 0.1 // 0..1
  11. #define x (Frequence * 2000 / SampleRate)
  12.  
  13. int counter = 0;
  14.  
  15. void audioCallback(void *userdata, Uint8 *stream, int len) {
  16. short buffer[BufferSizeInSamples];
  17. int i;
  18. for(i = 0; i < BufferSizeInSamples; i++)
  19. buffer[i] = (short)(sin((float)((counter + i) % x) / x * 2 * PI) * 32767);
  20. SDL_MixAudio(stream, (const Uint8 *)buffer, BufferSizeInBytes, SDL_MIX_MAXVOLUME * Volume);
  21. counter = counter + BufferSizeInSamples;
  22. }
  23.  
  24. int main(int argc, char* argv[]) {
  25. if(SDL_Init(SDL_INIT_AUDIO) < 0) {
  26. printf("Init() failed");
  27. return -1;
  28. }
  29. SDL_AudioSpec audioSpec;
  30. audioSpec.freq = SampleRate;
  31. audioSpec.format = AUDIO_S16;
  32. audioSpec.channels = 1;
  33. audioSpec.samples = BufferSizeInBytes;
  34. audioSpec.callback = audioCallback;
  35. audioSpec.userdata = NULL;
  36. if(SDL_OpenAudio(&audioSpec, NULL) < 0 ) {
  37. printf("OpenAudio() failed");
  38. return -1;
  39. }
  40. SDL_PauseAudio(0);
  41. // run program for 2 seconds
  42. int t = 2000;
  43. while(t > 0) {
  44. SDL_Delay(100);
  45. t = t - 100;
  46. }
  47. }
Advertisement
Add Comment
Please, Sign In to add comment