01_play_wav.cpp 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. #include <cstdio>
  2. #include <cerrno>
  3. #include <thread>
  4. #include <chrono>
  5. #include <cmath>
  6. #include <algorithm>
  7. #include <atomic>
  8. #include "simple/musical/initializer.h"
  9. #include "simple/musical/device.h"
  10. #include "simple/musical/wav.h"
  11. using namespace simple::musical;
  12. using namespace std::literals;
  13. int main(int argc, const char** argv) try
  14. {
  15. if(argc < 2)
  16. {
  17. std::puts("WAV file not specified");
  18. return -1;
  19. }
  20. initializer init;
  21. wav music(argv[1]);
  22. std::atomic<bool> done = false;
  23. device_with_callback player
  24. (
  25. basic_device_parameters{music.obtained()},
  26. [&done, &music, i = music.buffer().begin()](auto& device, auto buffer) mutable
  27. {
  28. const int remaining = music.buffer().end() - i;
  29. const int buffer_size = buffer.end() - buffer.begin();
  30. const int size = std::min<int>(remaining, buffer_size);
  31. const int extra = buffer_size - size;
  32. std::copy(i, i + size, buffer.begin());
  33. std::fill_n(buffer.begin() + size, extra, device.silence());
  34. i += size;
  35. if(i == music.buffer().end())
  36. done = true;
  37. }
  38. );
  39. player.play();
  40. while(!done)
  41. std::this_thread::sleep_for(50ms);
  42. return 0;
  43. }
  44. catch(...)
  45. {
  46. if(errno)
  47. std::perror("ERROR");
  48. const char* sdl_error = SDL_GetError();
  49. if(*sdl_error)
  50. std::puts(sdl_error);
  51. throw;
  52. }