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.

377 lines
14KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE examples.
  4. Copyright (c) 2020 - 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, vs2019, 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 : 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 audioDeviceIOCallback (const float** inputChannelData, int numInputChannels,
  108. float** outputChannelData, int numOutputChannels,
  109. int numSamples) override
  110. {
  111. const ScopedLock sl (writerLock);
  112. if (activeWriter.load() != nullptr && numInputChannels >= thumbnail.getNumChannels())
  113. {
  114. activeWriter.load()->write (inputChannelData, numSamples);
  115. // Create an AudioBuffer to wrap our incoming data, note that this does no allocations or copies, it simply references our input data
  116. AudioBuffer<float> buffer (const_cast<float**> (inputChannelData), thumbnail.getNumChannels(), numSamples);
  117. thumbnail.addBlock (nextSampleNum, buffer, 0, numSamples);
  118. nextSampleNum += numSamples;
  119. }
  120. // We need to clear the output buffers, in case they're full of junk..
  121. for (int i = 0; i < numOutputChannels; ++i)
  122. if (outputChannelData[i] != nullptr)
  123. FloatVectorOperations::clear (outputChannelData[i], numSamples);
  124. }
  125. private:
  126. AudioThumbnail& thumbnail;
  127. TimeSliceThread backgroundThread { "Audio Recorder Thread" }; // the thread that will write our audio data to disk
  128. std::unique_ptr<AudioFormatWriter::ThreadedWriter> threadedWriter; // the FIFO used to buffer the incoming data
  129. double sampleRate = 0.0;
  130. int64 nextSampleNum = 0;
  131. CriticalSection writerLock;
  132. std::atomic<AudioFormatWriter::ThreadedWriter*> activeWriter { nullptr };
  133. };
  134. //==============================================================================
  135. class RecordingThumbnail : public Component,
  136. private ChangeListener
  137. {
  138. public:
  139. RecordingThumbnail()
  140. {
  141. formatManager.registerBasicFormats();
  142. thumbnail.addChangeListener (this);
  143. }
  144. ~RecordingThumbnail() override
  145. {
  146. thumbnail.removeChangeListener (this);
  147. }
  148. AudioThumbnail& getAudioThumbnail() { return thumbnail; }
  149. void setDisplayFullThumbnail (bool displayFull)
  150. {
  151. displayFullThumb = displayFull;
  152. repaint();
  153. }
  154. void paint (Graphics& g) override
  155. {
  156. g.fillAll (Colours::darkgrey);
  157. g.setColour (Colours::lightgrey);
  158. if (thumbnail.getTotalLength() > 0.0)
  159. {
  160. auto endTime = displayFullThumb ? thumbnail.getTotalLength()
  161. : jmax (30.0, thumbnail.getTotalLength());
  162. auto thumbArea = getLocalBounds();
  163. thumbnail.drawChannels (g, thumbArea.reduced (2), 0.0, endTime, 1.0f);
  164. }
  165. else
  166. {
  167. g.setFont (14.0f);
  168. g.drawFittedText ("(No file recorded)", getLocalBounds(), Justification::centred, 2);
  169. }
  170. }
  171. private:
  172. AudioFormatManager formatManager;
  173. AudioThumbnailCache thumbnailCache { 10 };
  174. AudioThumbnail thumbnail { 512, formatManager, thumbnailCache };
  175. bool displayFullThumb = false;
  176. void changeListenerCallback (ChangeBroadcaster* source) override
  177. {
  178. if (source == &thumbnail)
  179. repaint();
  180. }
  181. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (RecordingThumbnail)
  182. };
  183. //==============================================================================
  184. class AudioRecordingDemo : public Component
  185. {
  186. public:
  187. AudioRecordingDemo()
  188. {
  189. setOpaque (true);
  190. addAndMakeVisible (liveAudioScroller);
  191. addAndMakeVisible (explanationLabel);
  192. explanationLabel.setFont (Font (15.0f, Font::plain));
  193. explanationLabel.setJustificationType (Justification::topLeft);
  194. explanationLabel.setEditable (false, false, false);
  195. explanationLabel.setColour (TextEditor::textColourId, Colours::black);
  196. explanationLabel.setColour (TextEditor::backgroundColourId, Colour (0x00000000));
  197. addAndMakeVisible (recordButton);
  198. recordButton.setColour (TextButton::buttonColourId, Colour (0xffff5c5c));
  199. recordButton.setColour (TextButton::textColourOnId, Colours::black);
  200. recordButton.onClick = [this]
  201. {
  202. if (recorder.isRecording())
  203. stopRecording();
  204. else
  205. startRecording();
  206. };
  207. addAndMakeVisible (recordingThumbnail);
  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 (&liveAudioScroller);
  217. audioDeviceManager.addAudioCallback (&recorder);
  218. setSize (500, 500);
  219. }
  220. ~AudioRecordingDemo() override
  221. {
  222. audioDeviceManager.removeAudioCallback (&recorder);
  223. audioDeviceManager.removeAudioCallback (&liveAudioScroller);
  224. }
  225. void paint (Graphics& g) override
  226. {
  227. g.fillAll (getUIColourIfAvailable (LookAndFeel_V4::ColourScheme::UIColour::windowBackground));
  228. }
  229. void resized() override
  230. {
  231. auto area = getLocalBounds();
  232. liveAudioScroller .setBounds (area.removeFromTop (80).reduced (8));
  233. recordingThumbnail.setBounds (area.removeFromTop (80).reduced (8));
  234. recordButton .setBounds (area.removeFromTop (36).removeFromLeft (140).reduced (8));
  235. explanationLabel .setBounds (area.reduced (8));
  236. }
  237. private:
  238. // if this PIP is running inside the demo runner, we'll use the shared device manager instead
  239. #ifndef JUCE_DEMO_RUNNER
  240. AudioDeviceManager audioDeviceManager;
  241. #else
  242. AudioDeviceManager& audioDeviceManager { getSharedAudioDeviceManager (1, 0) };
  243. #endif
  244. LiveScrollingAudioDisplay liveAudioScroller;
  245. RecordingThumbnail recordingThumbnail;
  246. AudioRecorder recorder { recordingThumbnail.getAudioThumbnail() };
  247. Label explanationLabel { {}, "This page demonstrates how to record a wave file from the live audio input..\n\n"
  248. #if (JUCE_ANDROID || JUCE_IOS)
  249. "After you are done with your recording you can share with other apps."
  250. #else
  251. "Pressing record will start recording a file in your \"Documents\" folder."
  252. #endif
  253. };
  254. TextButton recordButton { "Record" };
  255. File lastRecording;
  256. void startRecording()
  257. {
  258. if (! RuntimePermissions::isGranted (RuntimePermissions::writeExternalStorage))
  259. {
  260. SafePointer<AudioRecordingDemo> safeThis (this);
  261. RuntimePermissions::request (RuntimePermissions::writeExternalStorage,
  262. [safeThis] (bool granted) mutable
  263. {
  264. if (granted)
  265. safeThis->startRecording();
  266. });
  267. return;
  268. }
  269. #if (JUCE_ANDROID || JUCE_IOS)
  270. auto parentDir = File::getSpecialLocation (File::tempDirectory);
  271. #else
  272. auto parentDir = File::getSpecialLocation (File::userDocumentsDirectory);
  273. #endif
  274. lastRecording = parentDir.getNonexistentChildFile ("JUCE Demo Audio Recording", ".wav");
  275. recorder.startRecording (lastRecording);
  276. recordButton.setButtonText ("Stop");
  277. recordingThumbnail.setDisplayFullThumbnail (false);
  278. }
  279. void stopRecording()
  280. {
  281. recorder.stop();
  282. #if JUCE_CONTENT_SHARING
  283. SafePointer<AudioRecordingDemo> safeThis (this);
  284. File fileToShare = lastRecording;
  285. ContentSharer::getInstance()->shareFiles (Array<URL> ({URL (fileToShare)}),
  286. [safeThis, fileToShare] (bool success, const String& error)
  287. {
  288. if (fileToShare.existsAsFile())
  289. fileToShare.deleteFile();
  290. if (! success && error.isNotEmpty())
  291. {
  292. NativeMessageBox::showMessageBoxAsync (AlertWindow::WarningIcon,
  293. "Sharing Error",
  294. error);
  295. }
  296. });
  297. #endif
  298. lastRecording = File();
  299. recordButton.setButtonText ("Record");
  300. recordingThumbnail.setDisplayFullThumbnail (true);
  301. }
  302. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioRecordingDemo)
  303. };