SoundSynthesis.cpp 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153
  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/Urho3D.h>
  23. #include <Urho3D/Audio/BufferedSoundStream.h>
  24. #include <Urho3D/Audio/SoundSource.h>
  25. #include <Urho3D/Core/CoreEvents.h>
  26. #include <Urho3D/Engine/Engine.h>
  27. #include <Urho3D/Input/Input.h>
  28. #include <Urho3D/IO/Log.h>
  29. #include <Urho3D/Scene/Node.h>
  30. #include <Urho3D/UI/Font.h>
  31. #include <Urho3D/UI/Text.h>
  32. #include <Urho3D/UI/UI.h>
  33. #include "SoundSynthesis.h"
  34. #include <Urho3D/DebugNew.h>
  35. // Expands to this example's entry-point
  36. DEFINE_APPLICATION_MAIN(SoundSynthesis)
  37. SoundSynthesis::SoundSynthesis(Context* context) :
  38. Sample(context),
  39. filter_(0.5f),
  40. accumulator_(0.0f),
  41. osc1_(0.0f),
  42. osc2_(180.0f)
  43. {
  44. }
  45. void SoundSynthesis::Start()
  46. {
  47. // Execute base class startup
  48. Sample::Start();
  49. // Create the sound stream & start playback
  50. CreateSound();
  51. // Create the UI content
  52. CreateInstructions();
  53. // Hook up to the frame update events
  54. SubscribeToEvents();
  55. }
  56. void SoundSynthesis::CreateSound()
  57. {
  58. // Sound source needs a node so that it is considered enabled
  59. node_ = new Node(context_);
  60. SoundSource* source = node_->CreateComponent<SoundSource>();
  61. soundStream_ = new BufferedSoundStream();
  62. // Set format: 44100 Hz, sixteen bit, mono
  63. soundStream_->SetFormat(44100, true, false);
  64. // Start playback. We don't have data in the stream yet, but the SoundSource will wait until there is data,
  65. // as the stream is by default in the "don't stop at end" mode
  66. source->Play(soundStream_);
  67. }
  68. void SoundSynthesis::UpdateSound()
  69. {
  70. // Try to keep 1/10 seconds of sound in the buffer, to avoid both dropouts and unnecessary latency
  71. float targetLength = 1.0f / 10.0f;
  72. float requiredLength = targetLength - soundStream_->GetBufferLength();
  73. if (requiredLength < 0.0f)
  74. return;
  75. unsigned numSamples = (unsigned)(soundStream_->GetFrequency() * requiredLength);
  76. if (!numSamples)
  77. return;
  78. // Allocate a new buffer and fill it with a simple two-oscillator algorithm. The sound is over-amplified
  79. // (distorted), clamped to the 16-bit range, and finally lowpass-filtered according to the coefficient
  80. SharedArrayPtr<signed short> newData(new signed short[numSamples]);
  81. for (unsigned i = 0; i < numSamples; ++i)
  82. {
  83. osc1_ = fmodf(osc1_ + 1.0f, 360.0f);
  84. osc2_ = fmodf(osc2_ + 1.002f, 360.0f);
  85. float newValue = Clamp((Sin(osc1_) + Sin(osc2_)) * 100000.0f, -32767.0f, 32767.0f);
  86. accumulator_ = Lerp(accumulator_, newValue, filter_);
  87. newData[i] = (int)accumulator_;
  88. }
  89. // Queue buffer to the stream for playback
  90. soundStream_->AddData(newData, numSamples * sizeof(signed short));
  91. }
  92. void SoundSynthesis::CreateInstructions()
  93. {
  94. ResourceCache* cache = GetSubsystem<ResourceCache>();
  95. UI* ui = GetSubsystem<UI>();
  96. // Construct new Text object, set string to display and font to use
  97. instructionText_ = ui->GetRoot()->CreateChild<Text>();
  98. instructionText_->SetText("Use cursor up and down to control sound filtering");
  99. instructionText_->SetFont(cache->GetResource<Font>("Fonts/Anonymous Pro.ttf"), 15);
  100. // Position the text relative to the screen center
  101. instructionText_->SetTextAlignment(HA_CENTER);
  102. instructionText_->SetHorizontalAlignment(HA_CENTER);
  103. instructionText_->SetVerticalAlignment(VA_CENTER);
  104. instructionText_->SetPosition(0, ui->GetRoot()->GetHeight() / 4);
  105. }
  106. void SoundSynthesis::SubscribeToEvents()
  107. {
  108. // Subscribe HandleUpdate() function for processing update events
  109. SubscribeToEvent(E_UPDATE, HANDLER(SoundSynthesis, HandleUpdate));
  110. }
  111. void SoundSynthesis::HandleUpdate(StringHash eventType, VariantMap& eventData)
  112. {
  113. using namespace Update;
  114. // Take the frame time step, which is stored as a float
  115. float timeStep = eventData[P_TIMESTEP].GetFloat();
  116. // Use keys to control the filter constant
  117. Input* input = GetSubsystem<Input>();
  118. if (input->GetKeyDown(KEY_UP))
  119. filter_ += timeStep * 0.5f;
  120. if (input->GetKeyDown(KEY_DOWN))
  121. filter_ -= timeStep * 0.5f;
  122. filter_ = Clamp(filter_, 0.01f, 1.0f);
  123. instructionText_->SetText("Use cursor up and down to control sound filtering\n"
  124. "Coefficient: " + String(filter_));
  125. UpdateSound();
  126. }