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.

558 lines
19KB

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