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.

550 lines
19KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE examples.
  4. Copyright (c) 2017 - ROLI Ltd.
  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, vs2017, 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()
  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. addAndMakeVisible (explanation);
  235. explanation.setFont (Font (14.00f, Font::plain));
  236. explanation.setJustificationType (Justification::bottomRight);
  237. explanation.setEditable (false, false, false);
  238. explanation.setColour (TextEditor::textColourId, Colours::black);
  239. explanation.setColour (TextEditor::backgroundColourId, Colour (0x00000000));
  240. addAndMakeVisible (zoomSlider);
  241. zoomSlider.setRange (0, 1, 0);
  242. zoomSlider.onValueChange = [this] { thumbnail->setZoomFactor (zoomSlider.getValue()); };
  243. zoomSlider.setSkewFactor (2);
  244. thumbnail.reset (new DemoThumbnailComp (formatManager, transportSource, zoomSlider));
  245. addAndMakeVisible (thumbnail.get());
  246. thumbnail->addChangeListener (this);
  247. addAndMakeVisible (startStopButton);
  248. startStopButton.setColour (TextButton::buttonColourId, Colour (0xff79ed7f));
  249. startStopButton.setColour (TextButton::textColourOffId, Colours::black);
  250. startStopButton.onClick = [this] { startOrStop(); };
  251. // audio setup
  252. formatManager.registerBasicFormats();
  253. thread.startThread (3);
  254. #if (JUCE_ANDROID || JUCE_IOS)
  255. addAndMakeVisible (chooseFileButton);
  256. chooseFileButton.addListener (this);
  257. #else
  258. addAndMakeVisible (fileTreeComp);
  259. directoryList.setDirectory (File::getSpecialLocation (File::userHomeDirectory), true, true);
  260. fileTreeComp.setColour (FileTreeComponent::backgroundColourId, Colours::lightgrey.withAlpha (0.6f));
  261. fileTreeComp.addListener (this);
  262. #endif
  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()
  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. explanation.setBounds (controls.removeFromRight (controls.getWidth() / 3));
  297. auto zoom = controls.removeFromTop (25);
  298. zoomLabel .setBounds (zoom.removeFromLeft (50));
  299. zoomSlider.setBounds (zoom);
  300. followTransportButton.setBounds (controls.removeFromTop (25));
  301. startStopButton .setBounds (controls);
  302. r.removeFromBottom (6);
  303. thumbnail->setBounds (r.removeFromBottom (140));
  304. r.removeFromBottom (6);
  305. #if (JUCE_ANDROID || JUCE_IOS)
  306. chooseFileButton.setBounds (r);
  307. #else
  308. fileTreeComp.setBounds (r);
  309. #endif
  310. }
  311. private:
  312. // if this PIP is running inside the demo runner, we'll use the shared device manager instead
  313. #ifndef JUCE_DEMO_RUNNER
  314. AudioDeviceManager audioDeviceManager;
  315. #else
  316. AudioDeviceManager& audioDeviceManager { getSharedAudioDeviceManager (0, 2) };
  317. #endif
  318. AudioFormatManager formatManager;
  319. TimeSliceThread thread { "audio file preview" };
  320. #if (JUCE_ANDROID || JUCE_IOS)
  321. std::unique_ptr<FileChooser> fileChooser;
  322. TextButton chooseFileButton {"Choose Audio File...", "Choose an audio file for playback"};
  323. #else
  324. DirectoryContentsList directoryList {nullptr, thread};
  325. FileTreeComponent fileTreeComp {directoryList};
  326. #endif
  327. URL currentAudioFile;
  328. AudioSourcePlayer audioSourcePlayer;
  329. AudioTransportSource transportSource;
  330. std::unique_ptr<AudioFormatReaderSource> currentAudioFileSource;
  331. std::unique_ptr<DemoThumbnailComp> thumbnail;
  332. Label zoomLabel { {}, "zoom:" },
  333. explanation { {}, "Select an audio file in the treeview above, and this page will display its waveform, and let you play it.." };
  334. Slider zoomSlider { Slider::LinearHorizontal, Slider::NoTextBox };
  335. ToggleButton followTransportButton { "Follow Transport" };
  336. TextButton startStopButton { "Play/Stop" };
  337. //==============================================================================
  338. void showAudioResource (URL resource)
  339. {
  340. if (loadURLIntoTransport (resource))
  341. currentAudioFile = static_cast<URL&&> (resource);
  342. zoomSlider.setValue (0, dontSendNotification);
  343. thumbnail->setURL (currentAudioFile);
  344. }
  345. bool loadURLIntoTransport (const URL& audioURL)
  346. {
  347. // unload the previous file source and delete it..
  348. transportSource.stop();
  349. transportSource.setSource (nullptr);
  350. currentAudioFileSource.reset();
  351. AudioFormatReader* reader = nullptr;
  352. #if ! JUCE_IOS
  353. if (audioURL.isLocalFile())
  354. {
  355. reader = formatManager.createReaderFor (audioURL.getLocalFile());
  356. }
  357. else
  358. #endif
  359. {
  360. if (reader == nullptr)
  361. reader = formatManager.createReaderFor (audioURL.createInputStream (false));
  362. }
  363. if (reader != nullptr)
  364. {
  365. currentAudioFileSource.reset (new AudioFormatReaderSource (reader, true));
  366. // ..and plug it into our transport source
  367. transportSource.setSource (currentAudioFileSource.get(),
  368. 32768, // tells it to buffer this many samples ahead
  369. &thread, // this is the background thread to use for reading-ahead
  370. reader->sampleRate); // allows for sample rate correction
  371. return true;
  372. }
  373. return false;
  374. }
  375. void startOrStop()
  376. {
  377. if (transportSource.isPlaying())
  378. {
  379. transportSource.stop();
  380. }
  381. else
  382. {
  383. transportSource.setPosition (0);
  384. transportSource.start();
  385. }
  386. }
  387. void updateFollowTransportState()
  388. {
  389. thumbnail->setFollowsTransport (followTransportButton.getToggleState());
  390. }
  391. #if (JUCE_ANDROID || JUCE_IOS)
  392. void buttonClicked (Button* btn) override
  393. {
  394. if (btn == &chooseFileButton && fileChooser.get() == nullptr)
  395. {
  396. SafePointer<AudioPlaybackDemo> safeThis (this);
  397. if (! RuntimePermissions::isGranted (RuntimePermissions::readExternalStorage))
  398. {
  399. RuntimePermissions::request (RuntimePermissions::readExternalStorage,
  400. [safeThis] (bool granted) mutable
  401. {
  402. if (granted)
  403. safeThis->buttonClicked (&safeThis->chooseFileButton);
  404. });
  405. return;
  406. }
  407. if (FileChooser::isPlatformDialogAvailable())
  408. {
  409. fileChooser.reset (new FileChooser ("Select an audio file...", File(), "*.wav;*.mp3;*.aif"));
  410. fileChooser->launchAsync (FileBrowserComponent::openMode | FileBrowserComponent::canSelectFiles,
  411. [safeThis] (const FileChooser& fc) mutable
  412. {
  413. if (safeThis != nullptr && fc.getURLResults().size() > 0)
  414. {
  415. auto u = fc.getURLResult();
  416. safeThis->showAudioResource (static_cast<URL&&> (u));
  417. }
  418. safeThis->fileChooser = nullptr;
  419. }, nullptr);
  420. }
  421. else
  422. {
  423. NativeMessageBox::showMessageBoxAsync (AlertWindow::WarningIcon, "Enable Code Signing",
  424. "You need to enable code-signing for your iOS project and enable \"iCloud Documents\" "
  425. "permissions to be able to open audio files on your iDevice. See: "
  426. "https://forum.juce.com/t/native-ios-android-file-choosers");
  427. }
  428. }
  429. }
  430. #else
  431. void selectionChanged() override
  432. {
  433. showAudioResource (URL (fileTreeComp.getSelectedFile()));
  434. }
  435. void fileClicked (const File&, const MouseEvent&) override {}
  436. void fileDoubleClicked (const File&) override {}
  437. void browserRootChanged (const File&) override {}
  438. #endif
  439. void changeListenerCallback (ChangeBroadcaster* source) override
  440. {
  441. if (source == thumbnail.get())
  442. showAudioResource (URL (thumbnail->getLastDroppedFile()));
  443. }
  444. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioPlaybackDemo)
  445. };