Loop.h 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. #include <iostream>
  2. #include <thread>
  3. #include <mutex>
  4. #include <chrono>
  5. #include <vector>
  6. #include "Bar.h"
  7. class Loop
  8. {
  9. std::thread loopThread;
  10. std::chrono::milliseconds lastBeatTime;
  11. unsigned short bpm;
  12. std::mutex bpmLock;
  13. bool stopNext;
  14. public:
  15. bool enabled;
  16. unsigned short currentBarIndex;
  17. unsigned short currentBeatIndex;
  18. std::vector<Bar> bars;
  19. Loop()
  20. : bpm(60), stopNext(false), enabled(false),
  21. currentBarIndex(0), currentBeatIndex(0), lastBeatTime(0),
  22. loopThread(&Loop::loop, this)
  23. {
  24. }
  25. ~Loop()
  26. {
  27. stopNext = true;
  28. loopThread.join();
  29. }
  30. void setBpm(unsigned short b)
  31. {
  32. bpmLock.lock();
  33. bpm = b;
  34. bpmLock.unlock();
  35. }
  36. unsigned short getBpm()
  37. {
  38. bpmLock.lock();
  39. unsigned short r = bpm;
  40. bpmLock.unlock();
  41. return r;
  42. }
  43. std::chrono::milliseconds getBeatDuration()
  44. {
  45. return std::chrono::milliseconds(
  46. (long long)((double)60 * 1000 / bpm)
  47. );
  48. }
  49. void start()
  50. {
  51. enabled = true;
  52. }
  53. void stop()
  54. {
  55. enabled = false;
  56. }
  57. private:
  58. std::chrono::milliseconds getMillisecondsSinceEpoch()
  59. {
  60. std::chrono::system_clock::time_point now = std::chrono::system_clock::now();
  61. std::chrono::system_clock::duration duration = now.time_since_epoch();
  62. return std::chrono::duration_cast<std::chrono::milliseconds>(duration);
  63. }
  64. void beat()
  65. {
  66. std::cout << "\a" << lastBeatTime.count() << std::endl;
  67. if(bars.size() > 0) {
  68. if(currentBarIndex >= bars.size()) {
  69. currentBarIndex = 0;
  70. }
  71. std::cout << "trigger bar#" << currentBarIndex << std::endl;
  72. currentBarIndex++;
  73. }
  74. lastBeatTime = getMillisecondsSinceEpoch();
  75. }
  76. void loop()
  77. {
  78. while(!stopNext) {
  79. if(enabled && (getMillisecondsSinceEpoch() - lastBeatTime) >= getBeatDuration()) {
  80. beat();
  81. }
  82. }
  83. }
  84. };