SoundSampleQueue.hpp 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. #ifndef MUMSI_SOUNDSAMPLEQUEUE_HPP
  2. #define MUMSI_SOUNDSAMPLEQUEUE_HPP
  3. #include <mutex>
  4. #include <memory>
  5. #include <cstring>
  6. #include <algorithm>
  7. template<typename SAMPLE_TYPE>
  8. class SoundSampleQueue {
  9. public:
  10. SoundSampleQueue()
  11. : start(0),
  12. stop(0) {
  13. buffer = new SAMPLE_TYPE[10000000];
  14. }
  15. ~SoundSampleQueue() {
  16. delete[] buffer;
  17. }
  18. void push_back(SAMPLE_TYPE *data, int length) {
  19. std::lock_guard<std::mutex> lock(accessMutex);
  20. for (int i = 0; i < length; ++i) {
  21. buffer[stop + i] = data[i];
  22. }
  23. stop += length;
  24. }
  25. int pop_front(SAMPLE_TYPE *data, int maxLength) {
  26. std::lock_guard<std::mutex> lock(accessMutex);
  27. int samplesToTake = std::min(stop - start, maxLength);
  28. for (int i = 0; i < samplesToTake; ++i) {
  29. data[i] = buffer[start + i];
  30. }
  31. start += samplesToTake;
  32. return samplesToTake;
  33. }
  34. private:
  35. int start;
  36. int stop;
  37. std::mutex accessMutex;
  38. SAMPLE_TYPE *buffer;
  39. };
  40. #endif //MUMSI_SOUNDSAMPLEQUEUE_HPP