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.

541 lines
19KB

  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: AudioPlaybackDemo
  20. version: 1.0.0
  21. vendor: JUCE
  22. website: http://juce.com
  23. description: Plays an audio 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. type: Component
  30. mainClass: AudioPlaybackDemo
  31. useLocalCopy: 1
  32. END_JUCE_PIP_METADATA
  33. *******************************************************************************/
  34. #pragma once
  35. #include "../Assets/DemoUtilities.h"
  36. class DemoThumbnailComp final : public Component,
  37. public ChangeListener,
  38. public FileDragAndDropTarget,
  39. public ChangeBroadcaster,
  40. private ScrollBar::Listener,
  41. private Timer
  42. {
  43. public:
  44. DemoThumbnailComp (AudioFormatManager& formatManager,
  45. AudioTransportSource& source,
  46. Slider& slider)
  47. : transportSource (source),
  48. zoomSlider (slider),
  49. thumbnail (512, formatManager, thumbnailCache)
  50. {
  51. thumbnail.addChangeListener (this);
  52. addAndMakeVisible (scrollbar);
  53. scrollbar.setRangeLimits (visibleRange);
  54. scrollbar.setAutoHide (false);
  55. scrollbar.addListener (this);
  56. currentPositionMarker.setFill (Colours::white.withAlpha (0.85f));
  57. addAndMakeVisible (currentPositionMarker);
  58. }
  59. ~DemoThumbnailComp() override
  60. {
  61. scrollbar.removeListener (this);
  62. thumbnail.removeChangeListener (this);
  63. }
  64. void setURL (const URL& url)
  65. {
  66. if (auto inputSource = makeInputSource (url))
  67. {
  68. thumbnail.setSource (inputSource.release());
  69. Range<double> newRange (0.0, thumbnail.getTotalLength());
  70. scrollbar.setRangeLimits (newRange);
  71. setRange (newRange);
  72. startTimerHz (40);
  73. }
  74. }
  75. URL getLastDroppedFile() const noexcept { return lastFileDropped; }
  76. void setZoomFactor (double amount)
  77. {
  78. if (thumbnail.getTotalLength() > 0)
  79. {
  80. auto newScale = jmax (0.001, thumbnail.getTotalLength() * (1.0 - jlimit (0.0, 0.99, amount)));
  81. auto timeAtCentre = xToTime ((float) getWidth() / 2.0f);
  82. setRange ({ timeAtCentre - newScale * 0.5, timeAtCentre + newScale * 0.5 });
  83. }
  84. }
  85. void setRange (Range<double> newRange)
  86. {
  87. visibleRange = newRange;
  88. scrollbar.setCurrentRange (visibleRange);
  89. updateCursorPosition();
  90. repaint();
  91. }
  92. void setFollowsTransport (bool shouldFollow)
  93. {
  94. isFollowingTransport = shouldFollow;
  95. }
  96. void paint (Graphics& g) override
  97. {
  98. g.fillAll (Colours::darkgrey);
  99. g.setColour (Colours::lightblue);
  100. if (thumbnail.getTotalLength() > 0.0)
  101. {
  102. auto thumbArea = getLocalBounds();
  103. thumbArea.removeFromBottom (scrollbar.getHeight() + 4);
  104. thumbnail.drawChannels (g, thumbArea.reduced (2),
  105. visibleRange.getStart(), visibleRange.getEnd(), 1.0f);
  106. }
  107. else
  108. {
  109. g.setFont (14.0f);
  110. g.drawFittedText ("(No audio file selected)", getLocalBounds(), Justification::centred, 2);
  111. }
  112. }
  113. void resized() override
  114. {
  115. scrollbar.setBounds (getLocalBounds().removeFromBottom (14).reduced (2));
  116. }
  117. void changeListenerCallback (ChangeBroadcaster*) override
  118. {
  119. // this method is called by the thumbnail when it has changed, so we should repaint it..
  120. repaint();
  121. }
  122. bool isInterestedInFileDrag (const StringArray& /*files*/) override
  123. {
  124. return true;
  125. }
  126. void filesDropped (const StringArray& files, int /*x*/, int /*y*/) override
  127. {
  128. lastFileDropped = URL (File (files[0]));
  129. sendChangeMessage();
  130. }
  131. void mouseDown (const MouseEvent& e) override
  132. {
  133. mouseDrag (e);
  134. }
  135. void mouseDrag (const MouseEvent& e) override
  136. {
  137. if (canMoveTransport())
  138. transportSource.setPosition (jmax (0.0, xToTime ((float) e.x)));
  139. }
  140. void mouseUp (const MouseEvent&) override
  141. {
  142. transportSource.start();
  143. }
  144. void mouseWheelMove (const MouseEvent&, const MouseWheelDetails& wheel) override
  145. {
  146. if (thumbnail.getTotalLength() > 0.0)
  147. {
  148. auto newStart = visibleRange.getStart() - wheel.deltaX * (visibleRange.getLength()) / 10.0;
  149. newStart = jlimit (0.0, jmax (0.0, thumbnail.getTotalLength() - (visibleRange.getLength())), newStart);
  150. if (canMoveTransport())
  151. setRange ({ newStart, newStart + visibleRange.getLength() });
  152. if (! approximatelyEqual (wheel.deltaY, 0.0f))
  153. zoomSlider.setValue (zoomSlider.getValue() - wheel.deltaY);
  154. repaint();
  155. }
  156. }
  157. private:
  158. AudioTransportSource& transportSource;
  159. Slider& zoomSlider;
  160. ScrollBar scrollbar { false };
  161. AudioThumbnailCache thumbnailCache { 5 };
  162. AudioThumbnail thumbnail;
  163. Range<double> visibleRange;
  164. bool isFollowingTransport = false;
  165. URL lastFileDropped;
  166. DrawableRectangle currentPositionMarker;
  167. float timeToX (const double time) const
  168. {
  169. if (visibleRange.getLength() <= 0)
  170. return 0;
  171. return (float) getWidth() * (float) ((time - visibleRange.getStart()) / visibleRange.getLength());
  172. }
  173. double xToTime (const float x) const
  174. {
  175. return (x / (float) getWidth()) * (visibleRange.getLength()) + visibleRange.getStart();
  176. }
  177. bool canMoveTransport() const noexcept
  178. {
  179. return ! (isFollowingTransport && transportSource.isPlaying());
  180. }
  181. void scrollBarMoved (ScrollBar* scrollBarThatHasMoved, double newRangeStart) override
  182. {
  183. if (scrollBarThatHasMoved == &scrollbar)
  184. if (! (isFollowingTransport && transportSource.isPlaying()))
  185. setRange (visibleRange.movedToStartAt (newRangeStart));
  186. }
  187. void timerCallback() override
  188. {
  189. if (canMoveTransport())
  190. updateCursorPosition();
  191. else
  192. setRange (visibleRange.movedToStartAt (transportSource.getCurrentPosition() - (visibleRange.getLength() / 2.0)));
  193. }
  194. void updateCursorPosition()
  195. {
  196. currentPositionMarker.setVisible (transportSource.isPlaying() || isMouseButtonDown());
  197. currentPositionMarker.setRectangle (Rectangle<float> (timeToX (transportSource.getCurrentPosition()) - 0.75f, 0,
  198. 1.5f, (float) (getHeight() - scrollbar.getHeight())));
  199. }
  200. };
  201. //==============================================================================
  202. class AudioPlaybackDemo final : public Component,
  203. #if (JUCE_ANDROID || JUCE_IOS)
  204. private Button::Listener,
  205. #else
  206. private FileBrowserListener,
  207. #endif
  208. private ChangeListener
  209. {
  210. public:
  211. AudioPlaybackDemo()
  212. {
  213. addAndMakeVisible (zoomLabel);
  214. zoomLabel.setFont (Font (15.00f, Font::plain));
  215. zoomLabel.setJustificationType (Justification::centredRight);
  216. zoomLabel.setEditable (false, false, false);
  217. zoomLabel.setColour (TextEditor::textColourId, Colours::black);
  218. zoomLabel.setColour (TextEditor::backgroundColourId, Colour (0x00000000));
  219. addAndMakeVisible (followTransportButton);
  220. followTransportButton.onClick = [this] { updateFollowTransportState(); };
  221. #if (JUCE_ANDROID || JUCE_IOS)
  222. addAndMakeVisible (chooseFileButton);
  223. chooseFileButton.addListener (this);
  224. #else
  225. addAndMakeVisible (fileTreeComp);
  226. directoryList.setDirectory (File::getSpecialLocation (File::userHomeDirectory), true, true);
  227. fileTreeComp.setTitle ("Files");
  228. fileTreeComp.setColour (FileTreeComponent::backgroundColourId, Colours::lightgrey.withAlpha (0.6f));
  229. fileTreeComp.addListener (this);
  230. addAndMakeVisible (explanation);
  231. explanation.setFont (Font (14.00f, Font::plain));
  232. explanation.setJustificationType (Justification::bottomRight);
  233. explanation.setEditable (false, false, false);
  234. explanation.setColour (TextEditor::textColourId, Colours::black);
  235. explanation.setColour (TextEditor::backgroundColourId, Colour (0x00000000));
  236. #endif
  237. addAndMakeVisible (zoomSlider);
  238. zoomSlider.setRange (0, 1, 0);
  239. zoomSlider.onValueChange = [this] { thumbnail->setZoomFactor (zoomSlider.getValue()); };
  240. zoomSlider.setSkewFactor (2);
  241. thumbnail = std::make_unique<DemoThumbnailComp> (formatManager, transportSource, zoomSlider);
  242. addAndMakeVisible (thumbnail.get());
  243. thumbnail->addChangeListener (this);
  244. addAndMakeVisible (startStopButton);
  245. startStopButton.setColour (TextButton::buttonColourId, Colour (0xff79ed7f));
  246. startStopButton.setColour (TextButton::textColourOffId, Colours::black);
  247. startStopButton.onClick = [this] { startOrStop(); };
  248. // audio setup
  249. formatManager.registerBasicFormats();
  250. thread.startThread (Thread::Priority::normal);
  251. #ifndef JUCE_DEMO_RUNNER
  252. audioDeviceManager.initialise (0, 2, nullptr, true, {}, nullptr);
  253. #endif
  254. audioDeviceManager.addAudioCallback (&audioSourcePlayer);
  255. audioSourcePlayer.setSource (&transportSource);
  256. setOpaque (true);
  257. setSize (500, 500);
  258. }
  259. ~AudioPlaybackDemo() override
  260. {
  261. transportSource .setSource (nullptr);
  262. audioSourcePlayer.setSource (nullptr);
  263. audioDeviceManager.removeAudioCallback (&audioSourcePlayer);
  264. #if (JUCE_ANDROID || JUCE_IOS)
  265. chooseFileButton.removeListener (this);
  266. #else
  267. fileTreeComp.removeListener (this);
  268. #endif
  269. thumbnail->removeChangeListener (this);
  270. }
  271. void paint (Graphics& g) override
  272. {
  273. g.fillAll (getUIColourIfAvailable (LookAndFeel_V4::ColourScheme::UIColour::windowBackground));
  274. }
  275. void resized() override
  276. {
  277. auto r = getLocalBounds().reduced (4);
  278. auto controls = r.removeFromBottom (90);
  279. auto controlRightBounds = controls.removeFromRight (controls.getWidth() / 3);
  280. #if (JUCE_ANDROID || JUCE_IOS)
  281. chooseFileButton.setBounds (controlRightBounds.reduced (10));
  282. #else
  283. explanation.setBounds (controlRightBounds);
  284. #endif
  285. auto zoom = controls.removeFromTop (25);
  286. zoomLabel .setBounds (zoom.removeFromLeft (50));
  287. zoomSlider.setBounds (zoom);
  288. followTransportButton.setBounds (controls.removeFromTop (25));
  289. startStopButton .setBounds (controls);
  290. r.removeFromBottom (6);
  291. #if JUCE_ANDROID || JUCE_IOS
  292. thumbnail->setBounds (r);
  293. #else
  294. thumbnail->setBounds (r.removeFromBottom (140));
  295. r.removeFromBottom (6);
  296. fileTreeComp.setBounds (r);
  297. #endif
  298. }
  299. private:
  300. // if this PIP is running inside the demo runner, we'll use the shared device manager instead
  301. #ifndef JUCE_DEMO_RUNNER
  302. AudioDeviceManager audioDeviceManager;
  303. #else
  304. AudioDeviceManager& audioDeviceManager { getSharedAudioDeviceManager (0, 2) };
  305. #endif
  306. AudioFormatManager formatManager;
  307. TimeSliceThread thread { "audio file preview" };
  308. #if (JUCE_ANDROID || JUCE_IOS)
  309. std::unique_ptr<FileChooser> fileChooser;
  310. TextButton chooseFileButton {"Choose Audio File...", "Choose an audio file for playback"};
  311. #else
  312. DirectoryContentsList directoryList {nullptr, thread};
  313. FileTreeComponent fileTreeComp {directoryList};
  314. Label explanation { {}, "Select an audio file in the treeview above, and this page will display its waveform, and let you play it.." };
  315. #endif
  316. URL currentAudioFile;
  317. AudioSourcePlayer audioSourcePlayer;
  318. AudioTransportSource transportSource;
  319. std::unique_ptr<AudioFormatReaderSource> currentAudioFileSource;
  320. std::unique_ptr<DemoThumbnailComp> thumbnail;
  321. Label zoomLabel { {}, "zoom:" };
  322. Slider zoomSlider { Slider::LinearHorizontal, Slider::NoTextBox };
  323. ToggleButton followTransportButton { "Follow Transport" };
  324. TextButton startStopButton { "Play/Stop" };
  325. //==============================================================================
  326. void showAudioResource (URL resource)
  327. {
  328. if (! loadURLIntoTransport (resource))
  329. {
  330. // Failed to load the audio file!
  331. jassertfalse;
  332. return;
  333. }
  334. currentAudioFile = std::move (resource);
  335. zoomSlider.setValue (0, dontSendNotification);
  336. thumbnail->setURL (currentAudioFile);
  337. }
  338. bool loadURLIntoTransport (const URL& audioURL)
  339. {
  340. // unload the previous file source and delete it..
  341. transportSource.stop();
  342. transportSource.setSource (nullptr);
  343. currentAudioFileSource.reset();
  344. const auto source = makeInputSource (audioURL);
  345. if (source == nullptr)
  346. return false;
  347. auto stream = rawToUniquePtr (source->createInputStream());
  348. if (stream == nullptr)
  349. return false;
  350. auto reader = rawToUniquePtr (formatManager.createReaderFor (std::move (stream)));
  351. if (reader == nullptr)
  352. return false;
  353. currentAudioFileSource = std::make_unique<AudioFormatReaderSource> (reader.release(), true);
  354. // ..and plug it into our transport source
  355. transportSource.setSource (currentAudioFileSource.get(),
  356. 32768, // tells it to buffer this many samples ahead
  357. &thread, // this is the background thread to use for reading-ahead
  358. currentAudioFileSource->getAudioFormatReader()->sampleRate); // allows for sample rate correction
  359. return true;
  360. }
  361. void startOrStop()
  362. {
  363. if (transportSource.isPlaying())
  364. {
  365. transportSource.stop();
  366. }
  367. else
  368. {
  369. transportSource.setPosition (0);
  370. transportSource.start();
  371. }
  372. }
  373. void updateFollowTransportState()
  374. {
  375. thumbnail->setFollowsTransport (followTransportButton.getToggleState());
  376. }
  377. #if (JUCE_ANDROID || JUCE_IOS)
  378. void buttonClicked (Button* btn) override
  379. {
  380. if (btn == &chooseFileButton && fileChooser.get() == nullptr)
  381. {
  382. if (! RuntimePermissions::isGranted (RuntimePermissions::readExternalStorage))
  383. {
  384. SafePointer<AudioPlaybackDemo> safeThis (this);
  385. RuntimePermissions::request (RuntimePermissions::readExternalStorage,
  386. [safeThis] (bool granted) mutable
  387. {
  388. if (safeThis != nullptr && granted)
  389. safeThis->buttonClicked (&safeThis->chooseFileButton);
  390. });
  391. return;
  392. }
  393. if (FileChooser::isPlatformDialogAvailable())
  394. {
  395. fileChooser = std::make_unique<FileChooser> ("Select an audio file...", File(), "*.wav;*.flac;*.aif");
  396. fileChooser->launchAsync (FileBrowserComponent::openMode | FileBrowserComponent::canSelectFiles,
  397. [this] (const FileChooser& fc) mutable
  398. {
  399. if (fc.getURLResults().size() > 0)
  400. {
  401. auto u = fc.getURLResult();
  402. showAudioResource (std::move (u));
  403. }
  404. fileChooser = nullptr;
  405. }, nullptr);
  406. }
  407. else
  408. {
  409. NativeMessageBox::showAsync (MessageBoxOptions()
  410. .withIconType (MessageBoxIconType::WarningIcon)
  411. .withTitle ("Enable Code Signing")
  412. .withMessage ("You need to enable code-signing for your iOS project and enable \"iCloud Documents\" "
  413. "permissions to be able to open audio files on your iDevice. See: "
  414. "https://forum.juce.com/t/native-ios-android-file-choosers"),
  415. nullptr);
  416. }
  417. }
  418. }
  419. #else
  420. void selectionChanged() override
  421. {
  422. showAudioResource (URL (fileTreeComp.getSelectedFile()));
  423. }
  424. void fileClicked (const File&, const MouseEvent&) override {}
  425. void fileDoubleClicked (const File&) override {}
  426. void browserRootChanged (const File&) override {}
  427. #endif
  428. void changeListenerCallback (ChangeBroadcaster* source) override
  429. {
  430. if (source == thumbnail.get())
  431. showAudioResource (URL (thumbnail->getLastDroppedFile()));
  432. }
  433. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioPlaybackDemo)
  434. };