Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

09_sound.cpp 2.6 KiB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. //
  2. // Lol Engine — Sound tutorial
  3. //
  4. // Copyright © 2011—2016 Sam Hocevar <sam@hocevar.net>
  5. //
  6. // Lol Engine is free software. It comes without any warranty, to
  7. // the extent permitted by applicable law. You can redistribute it
  8. // and/or modify it under the terms of the Do What the Fuck You Want
  9. // to Public License, Version 2, as published by the WTFPL Task Force.
  10. // See http://www.wtfpl.net/ for more details.
  11. //
  12. #if HAVE_CONFIG_H
  13. # include "config.h"
  14. #endif
  15. #include <lol/engine.h>
  16. #include <functional>
  17. using namespace lol;
  18. class sound_demo : public WorldEntity
  19. {
  20. public:
  21. sound_demo()
  22. {
  23. for (auto &val : m_streams)
  24. val = -1;
  25. m_text = new Text("SPACE for sine wave, Left Click for white noise",
  26. "data/font/ascii.png");
  27. m_text->SetPos(vec3(5, 5, 1));
  28. Ticker::Ref(m_text);
  29. }
  30. ~sound_demo()
  31. {
  32. Ticker::Unref(m_text);
  33. }
  34. void synth(int mode, void *buf, int bytes)
  35. {
  36. uint16_t *stream = (uint16_t *)buf;
  37. for (int i = 0; i < bytes / 2; ++i)
  38. {
  39. switch (mode)
  40. {
  41. case 0: // sine wave
  42. stream[i] = 400 * lol::sin(12 * i * F_TAU / bytes);
  43. break;
  44. case 1: // white noise
  45. stream[i] = lol::rand(-120, 120);
  46. break;
  47. }
  48. }
  49. }
  50. virtual void tick_game(float seconds)
  51. {
  52. WorldEntity::tick_game(seconds);
  53. auto mouse = input::mouse();
  54. auto keyboard = input::keyboard();
  55. for (int i = 0; i < 2; ++i)
  56. {
  57. if (i == 0 && !keyboard->key_pressed(input::key::SC_Space))
  58. continue;
  59. if (i == 1 && !mouse->button_pressed(input::button::BTN_Left))
  60. continue;
  61. if (m_streams[i] < 0)
  62. {
  63. auto f = std::bind(&sound_demo::synth, this, i,
  64. std::placeholders::_1,
  65. std::placeholders::_2);
  66. m_streams[i] = audio::start_streaming(f);
  67. }
  68. else
  69. {
  70. audio::stop_streaming(m_streams[i]);
  71. m_streams[i] = -1;
  72. }
  73. }
  74. }
  75. virtual void tick_draw(float seconds, Scene &scene)
  76. {
  77. WorldEntity::tick_draw(seconds, scene);
  78. }
  79. private:
  80. int m_streams[2];
  81. Text *m_text;
  82. };
  83. int main(int argc, char **argv)
  84. {
  85. sys::init(argc, argv);
  86. Application app("Tutorial 9: Sound", ivec2(640, 480), 60.0f);
  87. new sound_demo();
  88. app.Run();
  89. return EXIT_SUCCESS;
  90. }