You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

113 rivejä
2.6 KiB

  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_controller = new Controller("Default");
  26. m_profile << InputProfile::KeyboardKey(0, "Space")
  27. << InputProfile::MouseKey(1, "Left");
  28. m_controller->Init(m_profile);
  29. m_text = new Text("SPACE for sine wave, Left Click for white noise",
  30. "data/font/ascii.png");
  31. m_text->SetPos(vec3(5, 5, 1));
  32. Ticker::Ref(m_text);
  33. }
  34. ~sound_demo()
  35. {
  36. Ticker::Unref(m_text);
  37. }
  38. void synth(int mode, void *buf, int bytes)
  39. {
  40. uint16_t *stream = (uint16_t *)buf;
  41. for (int i = 0; i < bytes / 2; ++i)
  42. {
  43. switch (mode)
  44. {
  45. case 0: // sine wave
  46. stream[i] = 400 * lol::sin(12 * i * F_TAU / bytes);
  47. break;
  48. case 1: // white noise
  49. stream[i] = lol::rand(-120, 120);
  50. break;
  51. }
  52. }
  53. }
  54. virtual void tick_game(float seconds)
  55. {
  56. WorldEntity::tick_game(seconds);
  57. for (int i = 0; i < 2; ++i)
  58. {
  59. if (!m_controller->WasKeyPressedThisFrame(i))
  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. Controller *m_controller;
  82. InputProfile m_profile;
  83. Text *m_text;
  84. };
  85. int main(int argc, char **argv)
  86. {
  87. sys::init(argc, argv);
  88. Application app("Tutorial 9: Sound", ivec2(640, 480), 60.0f);
  89. new sound_demo();
  90. app.Run();
  91. return EXIT_SUCCESS;
  92. }