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.

359 lines
14KB

  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 final : public SynthesiserSound
  41. {
  42. bool appliesToNote (int /*midiNoteNumber*/) override { return true; }
  43. bool appliesToChannel (int /*midiChannel*/) override { return true; }
  44. };
  45. //==============================================================================
  46. /** Our demo synth voice just plays a sine wave.. */
  47. struct SineWaveVoice final : public SynthesiserVoice
  48. {
  49. bool canPlaySound (SynthesiserSound* sound) override
  50. {
  51. return dynamic_cast<SineWaveSound*> (sound) != nullptr;
  52. }
  53. void startNote (int midiNoteNumber, float velocity,
  54. SynthesiserSound*, int /*currentPitchWheelPosition*/) override
  55. {
  56. currentAngle = 0.0;
  57. level = velocity * 0.15;
  58. tailOff = 0.0;
  59. auto cyclesPerSecond = MidiMessage::getMidiNoteInHertz (midiNoteNumber);
  60. auto cyclesPerSample = cyclesPerSecond / getSampleRate();
  61. angleDelta = cyclesPerSample * MathConstants<double>::twoPi;
  62. }
  63. void stopNote (float /*velocity*/, bool allowTailOff) override
  64. {
  65. if (allowTailOff)
  66. {
  67. // start a tail-off by setting this flag. The render callback will pick up on
  68. // this and do a fade out, calling clearCurrentNote() when it's finished.
  69. if (approximatelyEqual (tailOff, 0.0)) // we only need to begin a tail-off if it's not already doing so - the
  70. tailOff = 1.0; // stopNote method could be called more than once.
  71. }
  72. else
  73. {
  74. // we're being told to stop playing immediately, so reset everything..
  75. clearCurrentNote();
  76. angleDelta = 0.0;
  77. }
  78. }
  79. void pitchWheelMoved (int /*newValue*/) override {}
  80. void controllerMoved (int /*controllerNumber*/, int /*newValue*/) override {}
  81. void renderNextBlock (AudioBuffer<float>& outputBuffer, int startSample, int numSamples) override
  82. {
  83. if (! approximatelyEqual (angleDelta, 0.0))
  84. {
  85. if (tailOff > 0.0)
  86. {
  87. while (--numSamples >= 0)
  88. {
  89. auto currentSample = (float) (std::sin (currentAngle) * level * tailOff);
  90. for (auto i = outputBuffer.getNumChannels(); --i >= 0;)
  91. outputBuffer.addSample (i, startSample, currentSample);
  92. currentAngle += angleDelta;
  93. ++startSample;
  94. tailOff *= 0.99;
  95. if (tailOff <= 0.005)
  96. {
  97. clearCurrentNote();
  98. angleDelta = 0.0;
  99. break;
  100. }
  101. }
  102. }
  103. else
  104. {
  105. while (--numSamples >= 0)
  106. {
  107. auto currentSample = (float) (std::sin (currentAngle) * level);
  108. for (auto i = outputBuffer.getNumChannels(); --i >= 0;)
  109. outputBuffer.addSample (i, startSample, currentSample);
  110. currentAngle += angleDelta;
  111. ++startSample;
  112. }
  113. }
  114. }
  115. }
  116. using SynthesiserVoice::renderNextBlock;
  117. private:
  118. double currentAngle = 0.0, angleDelta = 0.0, level = 0.0, tailOff = 0.0;
  119. };
  120. //==============================================================================
  121. // This is an audio source that streams the output of our demo synth.
  122. struct SynthAudioSource final : public AudioSource
  123. {
  124. SynthAudioSource (MidiKeyboardState& keyState) : keyboardState (keyState)
  125. {
  126. // Add some voices to our synth, to play the sounds..
  127. for (auto i = 0; i < 4; ++i)
  128. {
  129. synth.addVoice (new SineWaveVoice()); // These voices will play our custom sine-wave sounds..
  130. synth.addVoice (new SamplerVoice()); // and these ones play the sampled sounds
  131. }
  132. // ..and add a sound for them to play...
  133. setUsingSineWaveSound();
  134. }
  135. void setUsingSineWaveSound()
  136. {
  137. synth.clearSounds();
  138. synth.addSound (new SineWaveSound());
  139. }
  140. void setUsingSampledSound()
  141. {
  142. WavAudioFormat wavFormat;
  143. std::unique_ptr<AudioFormatReader> audioReader (wavFormat.createReaderFor (createAssetInputStream ("cello.wav").release(), true));
  144. BigInteger allNotes;
  145. allNotes.setRange (0, 128, true);
  146. synth.clearSounds();
  147. synth.addSound (new SamplerSound ("demo sound",
  148. *audioReader,
  149. allNotes,
  150. 74, // root midi note
  151. 0.1, // attack time
  152. 0.1, // release time
  153. 10.0 // maximum sample length
  154. ));
  155. }
  156. void prepareToPlay (int /*samplesPerBlockExpected*/, double sampleRate) override
  157. {
  158. midiCollector.reset (sampleRate);
  159. synth.setCurrentPlaybackSampleRate (sampleRate);
  160. }
  161. void releaseResources() override {}
  162. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill) override
  163. {
  164. // the synth always adds its output to the audio buffer, so we have to clear it
  165. // first..
  166. bufferToFill.clearActiveBufferRegion();
  167. // fill a midi buffer with incoming messages from the midi input.
  168. MidiBuffer incomingMidi;
  169. midiCollector.removeNextBlockOfMessages (incomingMidi, bufferToFill.numSamples);
  170. // pass these messages to the keyboard state so that it can update the component
  171. // to show on-screen which keys are being pressed on the physical midi keyboard.
  172. // This call will also add midi messages to the buffer which were generated by
  173. // the mouse-clicking on the on-screen keyboard.
  174. keyboardState.processNextMidiBuffer (incomingMidi, 0, bufferToFill.numSamples, true);
  175. // and now get the synth to process the midi events and generate its output.
  176. synth.renderNextBlock (*bufferToFill.buffer, incomingMidi, 0, bufferToFill.numSamples);
  177. }
  178. //==============================================================================
  179. // this collects real-time midi messages from the midi input device, and
  180. // turns them into blocks that we can process in our audio callback
  181. MidiMessageCollector midiCollector;
  182. // this represents the state of which keys on our on-screen keyboard are held
  183. // down. When the mouse is clicked on the keyboard component, this object also
  184. // generates midi messages for this, which we can pass on to our synth.
  185. MidiKeyboardState& keyboardState;
  186. // the synth itself!
  187. Synthesiser synth;
  188. };
  189. //==============================================================================
  190. class Callback final : public AudioIODeviceCallback
  191. {
  192. public:
  193. Callback (AudioSourcePlayer& playerIn, LiveScrollingAudioDisplay& displayIn)
  194. : player (playerIn), display (displayIn) {}
  195. void audioDeviceIOCallbackWithContext (const float* const* inputChannelData,
  196. int numInputChannels,
  197. float* const* outputChannelData,
  198. int numOutputChannels,
  199. int numSamples,
  200. const AudioIODeviceCallbackContext& context) override
  201. {
  202. player.audioDeviceIOCallbackWithContext (inputChannelData,
  203. numInputChannels,
  204. outputChannelData,
  205. numOutputChannels,
  206. numSamples,
  207. context);
  208. display.audioDeviceIOCallbackWithContext (outputChannelData,
  209. numOutputChannels,
  210. nullptr,
  211. 0,
  212. numSamples,
  213. context);
  214. }
  215. void audioDeviceAboutToStart (AudioIODevice* device) override
  216. {
  217. player.audioDeviceAboutToStart (device);
  218. display.audioDeviceAboutToStart (device);
  219. }
  220. void audioDeviceStopped() override
  221. {
  222. player.audioDeviceStopped();
  223. display.audioDeviceStopped();
  224. }
  225. private:
  226. AudioSourcePlayer& player;
  227. LiveScrollingAudioDisplay& display;
  228. };
  229. //==============================================================================
  230. class AudioSynthesiserDemo final : public Component
  231. {
  232. public:
  233. AudioSynthesiserDemo()
  234. {
  235. addAndMakeVisible (keyboardComponent);
  236. addAndMakeVisible (sineButton);
  237. sineButton.setRadioGroupId (321);
  238. sineButton.setToggleState (true, dontSendNotification);
  239. sineButton.onClick = [this] { synthAudioSource.setUsingSineWaveSound(); };
  240. addAndMakeVisible (sampledButton);
  241. sampledButton.setRadioGroupId (321);
  242. sampledButton.onClick = [this] { synthAudioSource.setUsingSampledSound(); };
  243. addAndMakeVisible (liveAudioDisplayComp);
  244. audioSourcePlayer.setSource (&synthAudioSource);
  245. #ifndef JUCE_DEMO_RUNNER
  246. audioDeviceManager.initialise (0, 2, nullptr, true, {}, nullptr);
  247. #endif
  248. audioDeviceManager.addAudioCallback (&callback);
  249. audioDeviceManager.addMidiInputDeviceCallback ({}, &(synthAudioSource.midiCollector));
  250. setOpaque (true);
  251. setSize (640, 480);
  252. }
  253. ~AudioSynthesiserDemo() override
  254. {
  255. audioSourcePlayer.setSource (nullptr);
  256. audioDeviceManager.removeMidiInputDeviceCallback ({}, &(synthAudioSource.midiCollector));
  257. audioDeviceManager.removeAudioCallback (&callback);
  258. }
  259. //==============================================================================
  260. void paint (Graphics& g) override
  261. {
  262. g.fillAll (getUIColourIfAvailable (LookAndFeel_V4::ColourScheme::UIColour::windowBackground));
  263. }
  264. void resized() override
  265. {
  266. keyboardComponent .setBounds (8, 96, getWidth() - 16, 64);
  267. sineButton .setBounds (16, 176, 150, 24);
  268. sampledButton .setBounds (16, 200, 150, 24);
  269. liveAudioDisplayComp.setBounds (8, 8, getWidth() - 16, 64);
  270. }
  271. private:
  272. // if this PIP is running inside the demo runner, we'll use the shared device manager instead
  273. #ifndef JUCE_DEMO_RUNNER
  274. AudioDeviceManager audioDeviceManager;
  275. #else
  276. AudioDeviceManager& audioDeviceManager { getSharedAudioDeviceManager (0, 2) };
  277. #endif
  278. MidiKeyboardState keyboardState;
  279. AudioSourcePlayer audioSourcePlayer;
  280. SynthAudioSource synthAudioSource { keyboardState };
  281. MidiKeyboardComponent keyboardComponent { keyboardState, MidiKeyboardComponent::horizontalKeyboard};
  282. ToggleButton sineButton { "Use sine wave" };
  283. ToggleButton sampledButton { "Use sampled sound" };
  284. LiveScrollingAudioDisplay liveAudioDisplayComp;
  285. Callback callback { audioSourcePlayer, liveAudioDisplayComp };
  286. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioSynthesiserDemo)
  287. };