SoundSynthesis.cpp 5.3 KB

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