SoundSynthesis.cpp 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  1. //
  2. // Copyright (c) 2008-2015 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include <Urho3D/Audio/BufferedSoundStream.h>
  23. #include <Urho3D/Audio/SoundSource.h>
  24. #include <Urho3D/Core/CoreEvents.h>
  25. #include <Urho3D/Engine/Engine.h>
  26. #include <Urho3D/Input/Input.h>
  27. #include <Urho3D/IO/Log.h>
  28. #include <Urho3D/Scene/Node.h>
  29. #include <Urho3D/UI/Font.h>
  30. #include <Urho3D/UI/Text.h>
  31. #include <Urho3D/UI/UI.h>
  32. #include "SoundSynthesis.h"
  33. #include <Urho3D/DebugNew.h>
  34. // Expands to this example's entry-point
  35. DEFINE_APPLICATION_MAIN(SoundSynthesis)
  36. SoundSynthesis::SoundSynthesis(Context* context) :
  37. Sample(context),
  38. filter_(0.5f),
  39. accumulator_(0.0f),
  40. osc1_(0.0f),
  41. osc2_(180.0f)
  42. {
  43. }
  44. void SoundSynthesis::Setup()
  45. {
  46. // Modify engine startup parameters
  47. Sample::Setup();
  48. engineParameters_["Sound"] = true;
  49. }
  50. void SoundSynthesis::Start()
  51. {
  52. // Execute base class startup
  53. Sample::Start();
  54. // Create the sound stream & start playback
  55. CreateSound();
  56. // Create the UI content
  57. CreateInstructions();
  58. // Hook up to the frame update events
  59. SubscribeToEvents();
  60. }
  61. void SoundSynthesis::CreateSound()
  62. {
  63. // Sound source needs a node so that it is considered enabled
  64. node_ = new Node(context_);
  65. SoundSource* source = node_->CreateComponent<SoundSource>();
  66. soundStream_ = new BufferedSoundStream();
  67. // Set format: 44100 Hz, sixteen bit, mono
  68. soundStream_->SetFormat(44100, true, false);
  69. // Start playback. We don't have data in the stream yet, but the SoundSource will wait until there is data,
  70. // as the stream is by default in the "don't stop at end" mode
  71. source->Play(soundStream_);
  72. }
  73. void SoundSynthesis::UpdateSound()
  74. {
  75. // Try to keep 1/10 seconds of sound in the buffer, to avoid both dropouts and unnecessary latency
  76. float targetLength = 1.0f / 10.0f;
  77. float requiredLength = targetLength - soundStream_->GetBufferLength();
  78. if (requiredLength < 0.0f)
  79. return;
  80. unsigned numSamples = (unsigned)(soundStream_->GetFrequency() * requiredLength);
  81. if (!numSamples)
  82. return;
  83. // Allocate a new buffer and fill it with a simple two-oscillator algorithm. The sound is over-amplified
  84. // (distorted), clamped to the 16-bit range, and finally lowpass-filtered according to the coefficient
  85. SharedArrayPtr<signed short> newData(new signed short[numSamples]);
  86. for (unsigned i = 0; i < numSamples; ++i)
  87. {
  88. osc1_ = fmodf(osc1_ + 1.0f, 360.0f);
  89. osc2_ = fmodf(osc2_ + 1.002f, 360.0f);
  90. float newValue = Clamp((Sin(osc1_) + Sin(osc2_)) * 100000.0f, -32767.0f, 32767.0f);
  91. accumulator_ = Lerp(accumulator_, newValue, filter_);
  92. newData[i] = (int)accumulator_;
  93. }
  94. // Queue buffer to the stream for playback
  95. soundStream_->AddData(newData, numSamples * sizeof(signed short));
  96. }
  97. void SoundSynthesis::CreateInstructions()
  98. {
  99. ResourceCache* cache = GetSubsystem<ResourceCache>();
  100. UI* ui = GetSubsystem<UI>();
  101. // Construct new Text object, set string to display and font to use
  102. instructionText_ = ui->GetRoot()->CreateChild<Text>();
  103. instructionText_->SetText("Use cursor up and down to control sound filtering");
  104. instructionText_->SetFont(cache->GetResource<Font>("Fonts/Anonymous Pro.ttf"), 15);
  105. // Position the text relative to the screen center
  106. instructionText_->SetTextAlignment(HA_CENTER);
  107. instructionText_->SetHorizontalAlignment(HA_CENTER);
  108. instructionText_->SetVerticalAlignment(VA_CENTER);
  109. instructionText_->SetPosition(0, ui->GetRoot()->GetHeight() / 4);
  110. }
  111. void SoundSynthesis::SubscribeToEvents()
  112. {
  113. // Subscribe HandleUpdate() function for processing update events
  114. SubscribeToEvent(E_UPDATE, URHO3D_HANDLER(SoundSynthesis, HandleUpdate));
  115. }
  116. void SoundSynthesis::HandleUpdate(StringHash eventType, VariantMap& eventData)
  117. {
  118. using namespace Update;
  119. // Take the frame time step, which is stored as a float
  120. float timeStep = eventData[P_TIMESTEP].GetFloat();
  121. // Use keys to control the filter constant
  122. Input* input = GetSubsystem<Input>();
  123. if (input->GetKeyDown(KEY_UP))
  124. filter_ += timeStep * 0.5f;
  125. if (input->GetKeyDown(KEY_DOWN))
  126. filter_ -= timeStep * 0.5f;
  127. filter_ = Clamp(filter_, 0.01f, 1.0f);
  128. instructionText_->SetText("Use cursor up and down to control sound filtering\n"
  129. "Coefficient: " + String(filter_));
  130. UpdateSound();
  131. }