The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
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.

323 lines
12KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE examples.
  4. Copyright (c) 2022 - Raw Material Software Limited
  5. The code included in this file is provided under the terms of the ISC license
  6. http://www.isc.org/downloads/software-support-policy/isc-license. Permission
  7. To use, copy, modify, and/or distribute this software for any purpose with or
  8. without fee is hereby granted provided that the above copyright notice and
  9. this permission notice appear in all copies.
  10. THE SOFTWARE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES,
  11. WHETHER EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR
  12. PURPOSE, ARE DISCLAIMED.
  13. ==============================================================================
  14. */
  15. /*******************************************************************************
  16. The block below describes the properties of this PIP. A PIP is a short snippet
  17. of code that can be read by the Projucer and used to generate a JUCE project.
  18. BEGIN_JUCE_PIP_METADATA
  19. name: AudioSynthesiserDemo
  20. version: 1.0.0
  21. vendor: JUCE
  22. website: http://juce.com
  23. description: Simple synthesiser application.
  24. dependencies: juce_audio_basics, juce_audio_devices, juce_audio_formats,
  25. juce_audio_processors, juce_audio_utils, juce_core,
  26. juce_data_structures, juce_events, juce_graphics,
  27. juce_gui_basics, juce_gui_extra
  28. exporters: xcode_mac, vs2022, linux_make, androidstudio, xcode_iphone
  29. moduleFlags: JUCE_STRICT_REFCOUNTEDPOINTER=1
  30. type: Component
  31. mainClass: AudioSynthesiserDemo
  32. useLocalCopy: 1
  33. END_JUCE_PIP_METADATA
  34. *******************************************************************************/
  35. #pragma once
  36. #include "../Assets/DemoUtilities.h"
  37. #include "../Assets/AudioLiveScrollingDisplay.h"
  38. //==============================================================================
  39. /** Our demo synth sound is just a basic sine wave.. */
  40. struct SineWaveSound : public SynthesiserSound
  41. {
  42. SineWaveSound() {}
  43. bool appliesToNote (int /*midiNoteNumber*/) override { return true; }
  44. bool appliesToChannel (int /*midiChannel*/) override { return true; }
  45. };
  46. //==============================================================================
  47. /** Our demo synth voice just plays a sine wave.. */
  48. struct SineWaveVoice : public SynthesiserVoice
  49. {
  50. SineWaveVoice() {}
  51. bool canPlaySound (SynthesiserSound* sound) override
  52. {
  53. return dynamic_cast<SineWaveSound*> (sound) != nullptr;
  54. }
  55. void startNote (int midiNoteNumber, float velocity,
  56. SynthesiserSound*, int /*currentPitchWheelPosition*/) override
  57. {
  58. currentAngle = 0.0;
  59. level = velocity * 0.15;
  60. tailOff = 0.0;
  61. auto cyclesPerSecond = MidiMessage::getMidiNoteInHertz (midiNoteNumber);
  62. auto cyclesPerSample = cyclesPerSecond / getSampleRate();
  63. angleDelta = cyclesPerSample * MathConstants<double>::twoPi;
  64. }
  65. void stopNote (float /*velocity*/, bool allowTailOff) override
  66. {
  67. if (allowTailOff)
  68. {
  69. // start a tail-off by setting this flag. The render callback will pick up on
  70. // this and do a fade out, calling clearCurrentNote() when it's finished.
  71. if (tailOff == 0.0) // we only need to begin a tail-off if it's not already doing so - the
  72. tailOff = 1.0; // stopNote method could be called more than once.
  73. }
  74. else
  75. {
  76. // we're being told to stop playing immediately, so reset everything..
  77. clearCurrentNote();
  78. angleDelta = 0.0;
  79. }
  80. }
  81. void pitchWheelMoved (int /*newValue*/) override {}
  82. void controllerMoved (int /*controllerNumber*/, int /*newValue*/) override {}
  83. void renderNextBlock (AudioBuffer<float>& outputBuffer, int startSample, int numSamples) override
  84. {
  85. if (angleDelta != 0.0)
  86. {
  87. if (tailOff > 0.0)
  88. {
  89. while (--numSamples >= 0)
  90. {
  91. auto currentSample = (float) (std::sin (currentAngle) * level * tailOff);
  92. for (auto i = outputBuffer.getNumChannels(); --i >= 0;)
  93. outputBuffer.addSample (i, startSample, currentSample);
  94. currentAngle += angleDelta;
  95. ++startSample;
  96. tailOff *= 0.99;
  97. if (tailOff <= 0.005)
  98. {
  99. clearCurrentNote();
  100. angleDelta = 0.0;
  101. break;
  102. }
  103. }
  104. }
  105. else
  106. {
  107. while (--numSamples >= 0)
  108. {
  109. auto currentSample = (float) (std::sin (currentAngle) * level);
  110. for (auto i = outputBuffer.getNumChannels(); --i >= 0;)
  111. outputBuffer.addSample (i, startSample, currentSample);
  112. currentAngle += angleDelta;
  113. ++startSample;
  114. }
  115. }
  116. }
  117. }
  118. using SynthesiserVoice::renderNextBlock;
  119. private:
  120. double currentAngle = 0.0, angleDelta = 0.0, level = 0.0, tailOff = 0.0;
  121. };
  122. //==============================================================================
  123. // This is an audio source that streams the output of our demo synth.
  124. struct SynthAudioSource : public AudioSource
  125. {
  126. SynthAudioSource (MidiKeyboardState& keyState) : keyboardState (keyState)
  127. {
  128. // Add some voices to our synth, to play the sounds..
  129. for (auto i = 0; i < 4; ++i)
  130. {
  131. synth.addVoice (new SineWaveVoice()); // These voices will play our custom sine-wave sounds..
  132. synth.addVoice (new SamplerVoice()); // and these ones play the sampled sounds
  133. }
  134. // ..and add a sound for them to play...
  135. setUsingSineWaveSound();
  136. }
  137. void setUsingSineWaveSound()
  138. {
  139. synth.clearSounds();
  140. synth.addSound (new SineWaveSound());
  141. }
  142. void setUsingSampledSound()
  143. {
  144. WavAudioFormat wavFormat;
  145. std::unique_ptr<AudioFormatReader> audioReader (wavFormat.createReaderFor (createAssetInputStream ("cello.wav").release(), true));
  146. BigInteger allNotes;
  147. allNotes.setRange (0, 128, true);
  148. synth.clearSounds();
  149. synth.addSound (new SamplerSound ("demo sound",
  150. *audioReader,
  151. allNotes,
  152. 74, // root midi note
  153. 0.1, // attack time
  154. 0.1, // release time
  155. 10.0 // maximum sample length
  156. ));
  157. }
  158. void prepareToPlay (int /*samplesPerBlockExpected*/, double sampleRate) override
  159. {
  160. midiCollector.reset (sampleRate);
  161. synth.setCurrentPlaybackSampleRate (sampleRate);
  162. }
  163. void releaseResources() override {}
  164. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill) override
  165. {
  166. // the synth always adds its output to the audio buffer, so we have to clear it
  167. // first..
  168. bufferToFill.clearActiveBufferRegion();
  169. // fill a midi buffer with incoming messages from the midi input.
  170. MidiBuffer incomingMidi;
  171. midiCollector.removeNextBlockOfMessages (incomingMidi, bufferToFill.numSamples);
  172. // pass these messages to the keyboard state so that it can update the component
  173. // to show on-screen which keys are being pressed on the physical midi keyboard.
  174. // This call will also add midi messages to the buffer which were generated by
  175. // the mouse-clicking on the on-screen keyboard.
  176. keyboardState.processNextMidiBuffer (incomingMidi, 0, bufferToFill.numSamples, true);
  177. // and now get the synth to process the midi events and generate its output.
  178. synth.renderNextBlock (*bufferToFill.buffer, incomingMidi, 0, bufferToFill.numSamples);
  179. }
  180. //==============================================================================
  181. // this collects real-time midi messages from the midi input device, and
  182. // turns them into blocks that we can process in our audio callback
  183. MidiMessageCollector midiCollector;
  184. // this represents the state of which keys on our on-screen keyboard are held
  185. // down. When the mouse is clicked on the keyboard component, this object also
  186. // generates midi messages for this, which we can pass on to our synth.
  187. MidiKeyboardState& keyboardState;
  188. // the synth itself!
  189. Synthesiser synth;
  190. };
  191. //==============================================================================
  192. class AudioSynthesiserDemo : public Component
  193. {
  194. public:
  195. AudioSynthesiserDemo()
  196. {
  197. addAndMakeVisible (keyboardComponent);
  198. addAndMakeVisible (sineButton);
  199. sineButton.setRadioGroupId (321);
  200. sineButton.setToggleState (true, dontSendNotification);
  201. sineButton.onClick = [this] { synthAudioSource.setUsingSineWaveSound(); };
  202. addAndMakeVisible (sampledButton);
  203. sampledButton.setRadioGroupId (321);
  204. sampledButton.onClick = [this] { synthAudioSource.setUsingSampledSound(); };
  205. addAndMakeVisible (liveAudioDisplayComp);
  206. audioDeviceManager.addAudioCallback (&liveAudioDisplayComp);
  207. audioSourcePlayer.setSource (&synthAudioSource);
  208. #ifndef JUCE_DEMO_RUNNER
  209. RuntimePermissions::request (RuntimePermissions::recordAudio,
  210. [this] (bool granted)
  211. {
  212. int numInputChannels = granted ? 2 : 0;
  213. audioDeviceManager.initialise (numInputChannels, 2, nullptr, true, {}, nullptr);
  214. });
  215. #endif
  216. audioDeviceManager.addAudioCallback (&audioSourcePlayer);
  217. audioDeviceManager.addMidiInputDeviceCallback ({}, &(synthAudioSource.midiCollector));
  218. setOpaque (true);
  219. setSize (640, 480);
  220. }
  221. ~AudioSynthesiserDemo() override
  222. {
  223. audioSourcePlayer.setSource (nullptr);
  224. audioDeviceManager.removeMidiInputDeviceCallback ({}, &(synthAudioSource.midiCollector));
  225. audioDeviceManager.removeAudioCallback (&audioSourcePlayer);
  226. audioDeviceManager.removeAudioCallback (&liveAudioDisplayComp);
  227. }
  228. //==============================================================================
  229. void paint (Graphics& g) override
  230. {
  231. g.fillAll (getUIColourIfAvailable (LookAndFeel_V4::ColourScheme::UIColour::windowBackground));
  232. }
  233. void resized() override
  234. {
  235. keyboardComponent .setBounds (8, 96, getWidth() - 16, 64);
  236. sineButton .setBounds (16, 176, 150, 24);
  237. sampledButton .setBounds (16, 200, 150, 24);
  238. liveAudioDisplayComp.setBounds (8, 8, getWidth() - 16, 64);
  239. }
  240. private:
  241. // if this PIP is running inside the demo runner, we'll use the shared device manager instead
  242. #ifndef JUCE_DEMO_RUNNER
  243. AudioDeviceManager audioDeviceManager;
  244. #else
  245. AudioDeviceManager& audioDeviceManager { getSharedAudioDeviceManager (0, 2) };
  246. #endif
  247. MidiKeyboardState keyboardState;
  248. AudioSourcePlayer audioSourcePlayer;
  249. SynthAudioSource synthAudioSource { keyboardState };
  250. MidiKeyboardComponent keyboardComponent { keyboardState, MidiKeyboardComponent::horizontalKeyboard};
  251. ToggleButton sineButton { "Use sine wave" };
  252. ToggleButton sampledButton { "Use sampled sound" };
  253. LiveScrollingAudioDisplay liveAudioDisplayComp;
  254. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioSynthesiserDemo)
  255. };