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.

366 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: AudioRecordingDemo
  20. version: 1.0.0
  21. vendor: JUCE
  22. website: http://juce.com
  23. description: Records audio to a file.
  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: AudioRecordingDemo
  32. useLocalCopy: 1
  33. END_JUCE_PIP_METADATA
  34. *******************************************************************************/
  35. #pragma once
  36. #include "../Assets/DemoUtilities.h"
  37. #include "../Assets/AudioLiveScrollingDisplay.h"
  38. //==============================================================================
  39. /** A simple class that acts as an AudioIODeviceCallback and writes the
  40. incoming audio data to a WAV file.
  41. */
  42. class AudioRecorder final : public AudioIODeviceCallback
  43. {
  44. public:
  45. AudioRecorder (AudioThumbnail& thumbnailToUpdate)
  46. : thumbnail (thumbnailToUpdate)
  47. {
  48. backgroundThread.startThread();
  49. }
  50. ~AudioRecorder() override
  51. {
  52. stop();
  53. }
  54. //==============================================================================
  55. void startRecording (const File& file)
  56. {
  57. stop();
  58. if (sampleRate > 0)
  59. {
  60. // Create an OutputStream to write to our destination file...
  61. file.deleteFile();
  62. if (auto fileStream = std::unique_ptr<FileOutputStream> (file.createOutputStream()))
  63. {
  64. // Now create a WAV writer object that writes to our output stream...
  65. WavAudioFormat wavFormat;
  66. if (auto writer = wavFormat.createWriterFor (fileStream.get(), sampleRate, 1, 16, {}, 0))
  67. {
  68. fileStream.release(); // (passes responsibility for deleting the stream to the writer object that is now using it)
  69. // Now we'll create one of these helper objects which will act as a FIFO buffer, and will
  70. // write the data to disk on our background thread.
  71. threadedWriter.reset (new AudioFormatWriter::ThreadedWriter (writer, backgroundThread, 32768));
  72. // Reset our recording thumbnail
  73. thumbnail.reset (writer->getNumChannels(), writer->getSampleRate());
  74. nextSampleNum = 0;
  75. // And now, swap over our active writer pointer so that the audio callback will start using it..
  76. const ScopedLock sl (writerLock);
  77. activeWriter = threadedWriter.get();
  78. }
  79. }
  80. }
  81. }
  82. void stop()
  83. {
  84. // First, clear this pointer to stop the audio callback from using our writer object..
  85. {
  86. const ScopedLock sl (writerLock);
  87. activeWriter = nullptr;
  88. }
  89. // Now we can delete the writer object. It's done in this order because the deletion could
  90. // take a little time while remaining data gets flushed to disk, so it's best to avoid blocking
  91. // the audio callback while this happens.
  92. threadedWriter.reset();
  93. }
  94. bool isRecording() const
  95. {
  96. return activeWriter.load() != nullptr;
  97. }
  98. //==============================================================================
  99. void audioDeviceAboutToStart (AudioIODevice* device) override
  100. {
  101. sampleRate = device->getCurrentSampleRate();
  102. }
  103. void audioDeviceStopped() override
  104. {
  105. sampleRate = 0;
  106. }
  107. void audioDeviceIOCallbackWithContext (const float* const* inputChannelData, int numInputChannels,
  108. float* const* outputChannelData, int numOutputChannels,
  109. int numSamples, const AudioIODeviceCallbackContext& context) override
  110. {
  111. ignoreUnused (context);
  112. const ScopedLock sl (writerLock);
  113. if (activeWriter.load() != nullptr && numInputChannels >= thumbnail.getNumChannels())
  114. {
  115. activeWriter.load()->write (inputChannelData, numSamples);
  116. // Create an AudioBuffer to wrap our incoming data, note that this does no allocations or copies, it simply references our input data
  117. AudioBuffer<float> buffer (const_cast<float**> (inputChannelData), thumbnail.getNumChannels(), numSamples);
  118. thumbnail.addBlock (nextSampleNum, buffer, 0, numSamples);
  119. nextSampleNum += numSamples;
  120. }
  121. // We need to clear the output buffers, in case they're full of junk..
  122. for (int i = 0; i < numOutputChannels; ++i)
  123. if (outputChannelData[i] != nullptr)
  124. FloatVectorOperations::clear (outputChannelData[i], numSamples);
  125. }
  126. private:
  127. AudioThumbnail& thumbnail;
  128. TimeSliceThread backgroundThread { "Audio Recorder Thread" }; // the thread that will write our audio data to disk
  129. std::unique_ptr<AudioFormatWriter::ThreadedWriter> threadedWriter; // the FIFO used to buffer the incoming data
  130. double sampleRate = 0.0;
  131. int64 nextSampleNum = 0;
  132. CriticalSection writerLock;
  133. std::atomic<AudioFormatWriter::ThreadedWriter*> activeWriter { nullptr };
  134. };
  135. //==============================================================================
  136. class RecordingThumbnail final : public Component,
  137. private ChangeListener
  138. {
  139. public:
  140. RecordingThumbnail()
  141. {
  142. formatManager.registerBasicFormats();
  143. thumbnail.addChangeListener (this);
  144. }
  145. ~RecordingThumbnail() override
  146. {
  147. thumbnail.removeChangeListener (this);
  148. }
  149. AudioThumbnail& getAudioThumbnail() { return thumbnail; }
  150. void setDisplayFullThumbnail (bool displayFull)
  151. {
  152. displayFullThumb = displayFull;
  153. repaint();
  154. }
  155. void paint (Graphics& g) override
  156. {
  157. g.fillAll (Colours::darkgrey);
  158. g.setColour (Colours::lightgrey);
  159. if (thumbnail.getTotalLength() > 0.0)
  160. {
  161. auto endTime = displayFullThumb ? thumbnail.getTotalLength()
  162. : jmax (30.0, thumbnail.getTotalLength());
  163. auto thumbArea = getLocalBounds();
  164. thumbnail.drawChannels (g, thumbArea.reduced (2), 0.0, endTime, 1.0f);
  165. }
  166. else
  167. {
  168. g.setFont (14.0f);
  169. g.drawFittedText ("(No file recorded)", getLocalBounds(), Justification::centred, 2);
  170. }
  171. }
  172. private:
  173. AudioFormatManager formatManager;
  174. AudioThumbnailCache thumbnailCache { 10 };
  175. AudioThumbnail thumbnail { 512, formatManager, thumbnailCache };
  176. bool displayFullThumb = false;
  177. void changeListenerCallback (ChangeBroadcaster* source) override
  178. {
  179. if (source == &thumbnail)
  180. repaint();
  181. }
  182. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (RecordingThumbnail)
  183. };
  184. //==============================================================================
  185. class AudioRecordingDemo final : public Component
  186. {
  187. public:
  188. AudioRecordingDemo()
  189. {
  190. setOpaque (true);
  191. addAndMakeVisible (liveAudioScroller);
  192. addAndMakeVisible (explanationLabel);
  193. explanationLabel.setFont (Font (15.0f, Font::plain));
  194. explanationLabel.setJustificationType (Justification::topLeft);
  195. explanationLabel.setEditable (false, false, false);
  196. explanationLabel.setColour (TextEditor::textColourId, Colours::black);
  197. explanationLabel.setColour (TextEditor::backgroundColourId, Colour (0x00000000));
  198. addAndMakeVisible (recordButton);
  199. recordButton.setColour (TextButton::buttonColourId, Colour (0xffff5c5c));
  200. recordButton.setColour (TextButton::textColourOnId, Colours::black);
  201. recordButton.onClick = [this]
  202. {
  203. if (recorder.isRecording())
  204. stopRecording();
  205. else
  206. startRecording();
  207. };
  208. addAndMakeVisible (recordingThumbnail);
  209. #ifndef JUCE_DEMO_RUNNER
  210. RuntimePermissions::request (RuntimePermissions::recordAudio,
  211. [this] (bool granted)
  212. {
  213. int numInputChannels = granted ? 2 : 0;
  214. audioDeviceManager.initialise (numInputChannels, 2, nullptr, true, {}, nullptr);
  215. });
  216. #endif
  217. audioDeviceManager.addAudioCallback (&liveAudioScroller);
  218. audioDeviceManager.addAudioCallback (&recorder);
  219. setSize (500, 500);
  220. }
  221. ~AudioRecordingDemo() override
  222. {
  223. audioDeviceManager.removeAudioCallback (&recorder);
  224. audioDeviceManager.removeAudioCallback (&liveAudioScroller);
  225. }
  226. void paint (Graphics& g) override
  227. {
  228. g.fillAll (getUIColourIfAvailable (LookAndFeel_V4::ColourScheme::UIColour::windowBackground));
  229. }
  230. void resized() override
  231. {
  232. auto area = getLocalBounds();
  233. liveAudioScroller .setBounds (area.removeFromTop (80).reduced (8));
  234. recordingThumbnail.setBounds (area.removeFromTop (80).reduced (8));
  235. recordButton .setBounds (area.removeFromTop (36).removeFromLeft (140).reduced (8));
  236. explanationLabel .setBounds (area.reduced (8));
  237. }
  238. private:
  239. // if this PIP is running inside the demo runner, we'll use the shared device manager instead
  240. #ifndef JUCE_DEMO_RUNNER
  241. AudioDeviceManager audioDeviceManager;
  242. #else
  243. AudioDeviceManager& audioDeviceManager { getSharedAudioDeviceManager (1, 0) };
  244. #endif
  245. LiveScrollingAudioDisplay liveAudioScroller;
  246. RecordingThumbnail recordingThumbnail;
  247. AudioRecorder recorder { recordingThumbnail.getAudioThumbnail() };
  248. Label explanationLabel { {},
  249. "This page demonstrates how to record a wave file from the live audio input.\n\n"
  250. "After you are done with your recording you can choose where to save it." };
  251. TextButton recordButton { "Record" };
  252. File lastRecording;
  253. FileChooser chooser { "Output file...", File::getCurrentWorkingDirectory().getChildFile ("recording.wav"), "*.wav" };
  254. void startRecording()
  255. {
  256. if (! RuntimePermissions::isGranted (RuntimePermissions::writeExternalStorage))
  257. {
  258. SafePointer<AudioRecordingDemo> safeThis (this);
  259. RuntimePermissions::request (RuntimePermissions::writeExternalStorage,
  260. [safeThis] (bool granted) mutable
  261. {
  262. if (granted)
  263. safeThis->startRecording();
  264. });
  265. return;
  266. }
  267. #if (JUCE_ANDROID || JUCE_IOS)
  268. auto parentDir = File::getSpecialLocation (File::tempDirectory);
  269. #else
  270. auto parentDir = File::getSpecialLocation (File::userDocumentsDirectory);
  271. #endif
  272. lastRecording = parentDir.getNonexistentChildFile ("JUCE Demo Audio Recording", ".wav");
  273. recorder.startRecording (lastRecording);
  274. recordButton.setButtonText ("Stop");
  275. recordingThumbnail.setDisplayFullThumbnail (false);
  276. }
  277. void stopRecording()
  278. {
  279. recorder.stop();
  280. chooser.launchAsync ( FileBrowserComponent::saveMode
  281. | FileBrowserComponent::canSelectFiles
  282. | FileBrowserComponent::warnAboutOverwriting,
  283. [this] (const FileChooser& c)
  284. {
  285. if (FileInputStream inputStream (lastRecording); inputStream.openedOk())
  286. if (const auto outputStream = makeOutputStream (c.getURLResult()))
  287. outputStream->writeFromInputStream (inputStream, -1);
  288. recordButton.setButtonText ("Record");
  289. recordingThumbnail.setDisplayFullThumbnail (true);
  290. });
  291. }
  292. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioRecordingDemo)
  293. };