migrating to the latest JUCE version
This commit is contained in:
@ -1,89 +1,89 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE library.
|
||||
Copyright (c) 2020 - Raw Material Software Limited
|
||||
|
||||
JUCE is an open source library subject to commercial or open-source
|
||||
licensing.
|
||||
|
||||
By using JUCE, you agree to the terms of both the JUCE 6 End-User License
|
||||
Agreement and JUCE Privacy Policy (both effective as of the 16th June 2020).
|
||||
|
||||
End User License Agreement: www.juce.com/juce-6-licence
|
||||
Privacy Policy: www.juce.com/juce-privacy-policy
|
||||
|
||||
Or: You may also use this code under the terms of the GPL v3 (see
|
||||
www.gnu.org/licenses).
|
||||
|
||||
JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
|
||||
EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
|
||||
DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
AudioAppComponent::AudioAppComponent()
|
||||
: deviceManager (defaultDeviceManager),
|
||||
usingCustomDeviceManager (false)
|
||||
{
|
||||
}
|
||||
|
||||
AudioAppComponent::AudioAppComponent (AudioDeviceManager& adm)
|
||||
: deviceManager (adm),
|
||||
usingCustomDeviceManager (true)
|
||||
{
|
||||
}
|
||||
|
||||
AudioAppComponent::~AudioAppComponent()
|
||||
{
|
||||
// If you hit this then your derived class must call shutdown audio in
|
||||
// destructor!
|
||||
jassert (audioSourcePlayer.getCurrentSource() == nullptr);
|
||||
}
|
||||
|
||||
void AudioAppComponent::setAudioChannels (int numInputChannels, int numOutputChannels, const XmlElement* const xml)
|
||||
{
|
||||
String audioError;
|
||||
|
||||
if (usingCustomDeviceManager && xml == nullptr)
|
||||
{
|
||||
auto setup = deviceManager.getAudioDeviceSetup();
|
||||
|
||||
if (setup.inputChannels.countNumberOfSetBits() != numInputChannels
|
||||
|| setup.outputChannels.countNumberOfSetBits() != numOutputChannels)
|
||||
{
|
||||
setup.inputChannels.clear();
|
||||
setup.outputChannels.clear();
|
||||
|
||||
setup.inputChannels.setRange (0, numInputChannels, true);
|
||||
setup.outputChannels.setRange (0, numOutputChannels, true);
|
||||
|
||||
audioError = deviceManager.setAudioDeviceSetup (setup, false);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
audioError = deviceManager.initialise (numInputChannels, numOutputChannels, xml, true);
|
||||
}
|
||||
|
||||
jassert (audioError.isEmpty());
|
||||
|
||||
deviceManager.addAudioCallback (&audioSourcePlayer);
|
||||
audioSourcePlayer.setSource (this);
|
||||
}
|
||||
|
||||
void AudioAppComponent::shutdownAudio()
|
||||
{
|
||||
audioSourcePlayer.setSource (nullptr);
|
||||
deviceManager.removeAudioCallback (&audioSourcePlayer);
|
||||
|
||||
// other audio callbacks may still be using the device
|
||||
if (! usingCustomDeviceManager)
|
||||
deviceManager.closeAudioDevice();
|
||||
}
|
||||
|
||||
} // namespace juce
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE library.
|
||||
Copyright (c) 2022 - Raw Material Software Limited
|
||||
|
||||
JUCE is an open source library subject to commercial or open-source
|
||||
licensing.
|
||||
|
||||
By using JUCE, you agree to the terms of both the JUCE 7 End-User License
|
||||
Agreement and JUCE Privacy Policy.
|
||||
|
||||
End User License Agreement: www.juce.com/juce-7-licence
|
||||
Privacy Policy: www.juce.com/juce-privacy-policy
|
||||
|
||||
Or: You may also use this code under the terms of the GPL v3 (see
|
||||
www.gnu.org/licenses).
|
||||
|
||||
JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
|
||||
EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
|
||||
DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
AudioAppComponent::AudioAppComponent()
|
||||
: deviceManager (defaultDeviceManager),
|
||||
usingCustomDeviceManager (false)
|
||||
{
|
||||
}
|
||||
|
||||
AudioAppComponent::AudioAppComponent (AudioDeviceManager& adm)
|
||||
: deviceManager (adm),
|
||||
usingCustomDeviceManager (true)
|
||||
{
|
||||
}
|
||||
|
||||
AudioAppComponent::~AudioAppComponent()
|
||||
{
|
||||
// If you hit this then your derived class must call shutdown audio in
|
||||
// destructor!
|
||||
jassert (audioSourcePlayer.getCurrentSource() == nullptr);
|
||||
}
|
||||
|
||||
void AudioAppComponent::setAudioChannels (int numInputChannels, int numOutputChannels, const XmlElement* const xml)
|
||||
{
|
||||
String audioError;
|
||||
|
||||
if (usingCustomDeviceManager && xml == nullptr)
|
||||
{
|
||||
auto setup = deviceManager.getAudioDeviceSetup();
|
||||
|
||||
if (setup.inputChannels.countNumberOfSetBits() != numInputChannels
|
||||
|| setup.outputChannels.countNumberOfSetBits() != numOutputChannels)
|
||||
{
|
||||
setup.inputChannels.clear();
|
||||
setup.outputChannels.clear();
|
||||
|
||||
setup.inputChannels.setRange (0, numInputChannels, true);
|
||||
setup.outputChannels.setRange (0, numOutputChannels, true);
|
||||
|
||||
audioError = deviceManager.setAudioDeviceSetup (setup, false);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
audioError = deviceManager.initialise (numInputChannels, numOutputChannels, xml, true);
|
||||
}
|
||||
|
||||
jassert (audioError.isEmpty());
|
||||
|
||||
deviceManager.addAudioCallback (&audioSourcePlayer);
|
||||
audioSourcePlayer.setSource (this);
|
||||
}
|
||||
|
||||
void AudioAppComponent::shutdownAudio()
|
||||
{
|
||||
audioSourcePlayer.setSource (nullptr);
|
||||
deviceManager.removeAudioCallback (&audioSourcePlayer);
|
||||
|
||||
// other audio callbacks may still be using the device
|
||||
if (! usingCustomDeviceManager)
|
||||
deviceManager.closeAudioDevice();
|
||||
}
|
||||
|
||||
} // namespace juce
|
||||
|
@ -1,135 +1,135 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE library.
|
||||
Copyright (c) 2020 - Raw Material Software Limited
|
||||
|
||||
JUCE is an open source library subject to commercial or open-source
|
||||
licensing.
|
||||
|
||||
By using JUCE, you agree to the terms of both the JUCE 6 End-User License
|
||||
Agreement and JUCE Privacy Policy (both effective as of the 16th June 2020).
|
||||
|
||||
End User License Agreement: www.juce.com/juce-6-licence
|
||||
Privacy Policy: www.juce.com/juce-privacy-policy
|
||||
|
||||
Or: You may also use this code under the terms of the GPL v3 (see
|
||||
www.gnu.org/licenses).
|
||||
|
||||
JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
|
||||
EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
|
||||
DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
//==============================================================================
|
||||
/**
|
||||
A base class for writing audio apps that stream from the audio i/o devices.
|
||||
Conveniently combines a Component with an AudioSource to provide a starting
|
||||
point for your audio applications.
|
||||
|
||||
A subclass can inherit from this and implement just a few methods such as
|
||||
getNextAudioBlock(). The base class provides a basic AudioDeviceManager object
|
||||
and runs audio through the default output device.
|
||||
|
||||
An application should only create one global instance of this object and multiple
|
||||
classes should not inherit from this.
|
||||
|
||||
This class should not be inherited when creating a plug-in as the host will
|
||||
handle audio streams from hardware devices.
|
||||
|
||||
@tags{Audio}
|
||||
*/
|
||||
class JUCE_API AudioAppComponent : public Component,
|
||||
public AudioSource
|
||||
{
|
||||
public:
|
||||
AudioAppComponent();
|
||||
AudioAppComponent (AudioDeviceManager&);
|
||||
|
||||
~AudioAppComponent() override;
|
||||
|
||||
/** A subclass should call this from their constructor, to set up the audio. */
|
||||
void setAudioChannels (int numInputChannels, int numOutputChannels, const XmlElement* const storedSettings = nullptr);
|
||||
|
||||
/** Tells the source to prepare for playing.
|
||||
|
||||
An AudioSource has two states: prepared and unprepared.
|
||||
|
||||
The prepareToPlay() method is guaranteed to be called at least once on an 'unprepared'
|
||||
source to put it into a 'prepared' state before any calls will be made to getNextAudioBlock().
|
||||
This callback allows the source to initialise any resources it might need when playing.
|
||||
|
||||
Once playback has finished, the releaseResources() method is called to put the stream
|
||||
back into an 'unprepared' state.
|
||||
|
||||
Note that this method could be called more than once in succession without
|
||||
a matching call to releaseResources(), so make sure your code is robust and
|
||||
can handle that kind of situation.
|
||||
|
||||
@param samplesPerBlockExpected the number of samples that the source
|
||||
will be expected to supply each time its
|
||||
getNextAudioBlock() method is called. This
|
||||
number may vary slightly, because it will be dependent
|
||||
on audio hardware callbacks, and these aren't
|
||||
guaranteed to always use a constant block size, so
|
||||
the source should be able to cope with small variations.
|
||||
@param sampleRate the sample rate that the output will be used at - this
|
||||
is needed by sources such as tone generators.
|
||||
@see releaseResources, getNextAudioBlock
|
||||
*/
|
||||
void prepareToPlay (int samplesPerBlockExpected,
|
||||
double sampleRate) override = 0;
|
||||
|
||||
/** Allows the source to release anything it no longer needs after playback has stopped.
|
||||
|
||||
This will be called when the source is no longer going to have its getNextAudioBlock()
|
||||
method called, so it should release any spare memory, etc. that it might have
|
||||
allocated during the prepareToPlay() call.
|
||||
|
||||
Note that there's no guarantee that prepareToPlay() will actually have been called before
|
||||
releaseResources(), and it may be called more than once in succession, so make sure your
|
||||
code is robust and doesn't make any assumptions about when it will be called.
|
||||
|
||||
@see prepareToPlay, getNextAudioBlock
|
||||
*/
|
||||
void releaseResources() override = 0;
|
||||
|
||||
/** Called repeatedly to fetch subsequent blocks of audio data.
|
||||
|
||||
After calling the prepareToPlay() method, this callback will be made each
|
||||
time the audio playback hardware (or whatever other destination the audio
|
||||
data is going to) needs another block of data.
|
||||
|
||||
It will generally be called on a high-priority system thread, or possibly even
|
||||
an interrupt, so be careful not to do too much work here, as that will cause
|
||||
audio glitches!
|
||||
|
||||
@see AudioSourceChannelInfo, prepareToPlay, releaseResources
|
||||
*/
|
||||
void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill) override = 0;
|
||||
|
||||
/** Shuts down the audio device and clears the audio source.
|
||||
|
||||
This method should be called in the destructor of the derived class
|
||||
otherwise an assertion will be triggered.
|
||||
*/
|
||||
void shutdownAudio();
|
||||
|
||||
|
||||
AudioDeviceManager& deviceManager;
|
||||
|
||||
private:
|
||||
//==============================================================================
|
||||
AudioDeviceManager defaultDeviceManager;
|
||||
AudioSourcePlayer audioSourcePlayer;
|
||||
bool usingCustomDeviceManager;
|
||||
|
||||
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioAppComponent)
|
||||
};
|
||||
|
||||
} // namespace juce
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE library.
|
||||
Copyright (c) 2022 - Raw Material Software Limited
|
||||
|
||||
JUCE is an open source library subject to commercial or open-source
|
||||
licensing.
|
||||
|
||||
By using JUCE, you agree to the terms of both the JUCE 7 End-User License
|
||||
Agreement and JUCE Privacy Policy.
|
||||
|
||||
End User License Agreement: www.juce.com/juce-7-licence
|
||||
Privacy Policy: www.juce.com/juce-privacy-policy
|
||||
|
||||
Or: You may also use this code under the terms of the GPL v3 (see
|
||||
www.gnu.org/licenses).
|
||||
|
||||
JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
|
||||
EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
|
||||
DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
//==============================================================================
|
||||
/**
|
||||
A base class for writing audio apps that stream from the audio i/o devices.
|
||||
Conveniently combines a Component with an AudioSource to provide a starting
|
||||
point for your audio applications.
|
||||
|
||||
A subclass can inherit from this and implement just a few methods such as
|
||||
getNextAudioBlock(). The base class provides a basic AudioDeviceManager object
|
||||
and runs audio through the default output device.
|
||||
|
||||
An application should only create one global instance of this object and multiple
|
||||
classes should not inherit from this.
|
||||
|
||||
This class should not be inherited when creating a plug-in as the host will
|
||||
handle audio streams from hardware devices.
|
||||
|
||||
@tags{Audio}
|
||||
*/
|
||||
class JUCE_API AudioAppComponent : public Component,
|
||||
public AudioSource
|
||||
{
|
||||
public:
|
||||
AudioAppComponent();
|
||||
AudioAppComponent (AudioDeviceManager&);
|
||||
|
||||
~AudioAppComponent() override;
|
||||
|
||||
/** A subclass should call this from their constructor, to set up the audio. */
|
||||
void setAudioChannels (int numInputChannels, int numOutputChannels, const XmlElement* const storedSettings = nullptr);
|
||||
|
||||
/** Tells the source to prepare for playing.
|
||||
|
||||
An AudioSource has two states: prepared and unprepared.
|
||||
|
||||
The prepareToPlay() method is guaranteed to be called at least once on an 'unprepared'
|
||||
source to put it into a 'prepared' state before any calls will be made to getNextAudioBlock().
|
||||
This callback allows the source to initialise any resources it might need when playing.
|
||||
|
||||
Once playback has finished, the releaseResources() method is called to put the stream
|
||||
back into an 'unprepared' state.
|
||||
|
||||
Note that this method could be called more than once in succession without
|
||||
a matching call to releaseResources(), so make sure your code is robust and
|
||||
can handle that kind of situation.
|
||||
|
||||
@param samplesPerBlockExpected the number of samples that the source
|
||||
will be expected to supply each time its
|
||||
getNextAudioBlock() method is called. This
|
||||
number may vary slightly, because it will be dependent
|
||||
on audio hardware callbacks, and these aren't
|
||||
guaranteed to always use a constant block size, so
|
||||
the source should be able to cope with small variations.
|
||||
@param sampleRate the sample rate that the output will be used at - this
|
||||
is needed by sources such as tone generators.
|
||||
@see releaseResources, getNextAudioBlock
|
||||
*/
|
||||
void prepareToPlay (int samplesPerBlockExpected,
|
||||
double sampleRate) override = 0;
|
||||
|
||||
/** Allows the source to release anything it no longer needs after playback has stopped.
|
||||
|
||||
This will be called when the source is no longer going to have its getNextAudioBlock()
|
||||
method called, so it should release any spare memory, etc. that it might have
|
||||
allocated during the prepareToPlay() call.
|
||||
|
||||
Note that there's no guarantee that prepareToPlay() will actually have been called before
|
||||
releaseResources(), and it may be called more than once in succession, so make sure your
|
||||
code is robust and doesn't make any assumptions about when it will be called.
|
||||
|
||||
@see prepareToPlay, getNextAudioBlock
|
||||
*/
|
||||
void releaseResources() override = 0;
|
||||
|
||||
/** Called repeatedly to fetch subsequent blocks of audio data.
|
||||
|
||||
After calling the prepareToPlay() method, this callback will be made each
|
||||
time the audio playback hardware (or whatever other destination the audio
|
||||
data is going to) needs another block of data.
|
||||
|
||||
It will generally be called on a high-priority system thread, or possibly even
|
||||
an interrupt, so be careful not to do too much work here, as that will cause
|
||||
audio glitches!
|
||||
|
||||
@see AudioSourceChannelInfo, prepareToPlay, releaseResources
|
||||
*/
|
||||
void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill) override = 0;
|
||||
|
||||
/** Shuts down the audio device and clears the audio source.
|
||||
|
||||
This method should be called in the destructor of the derived class
|
||||
otherwise an assertion will be triggered.
|
||||
*/
|
||||
void shutdownAudio();
|
||||
|
||||
|
||||
AudioDeviceManager& deviceManager;
|
||||
|
||||
private:
|
||||
//==============================================================================
|
||||
AudioDeviceManager defaultDeviceManager;
|
||||
AudioSourcePlayer audioSourcePlayer;
|
||||
bool usingCustomDeviceManager;
|
||||
|
||||
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioAppComponent)
|
||||
};
|
||||
|
||||
} // namespace juce
|
||||
|
File diff suppressed because it is too large
Load Diff
@ -1,121 +1,119 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE library.
|
||||
Copyright (c) 2020 - Raw Material Software Limited
|
||||
|
||||
JUCE is an open source library subject to commercial or open-source
|
||||
licensing.
|
||||
|
||||
By using JUCE, you agree to the terms of both the JUCE 6 End-User License
|
||||
Agreement and JUCE Privacy Policy (both effective as of the 16th June 2020).
|
||||
|
||||
End User License Agreement: www.juce.com/juce-6-licence
|
||||
Privacy Policy: www.juce.com/juce-privacy-policy
|
||||
|
||||
Or: You may also use this code under the terms of the GPL v3 (see
|
||||
www.gnu.org/licenses).
|
||||
|
||||
JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
|
||||
EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
|
||||
DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
//==============================================================================
|
||||
/**
|
||||
A component containing controls to let the user change the audio settings of
|
||||
an AudioDeviceManager object.
|
||||
|
||||
Very easy to use - just create one of these and show it to the user.
|
||||
|
||||
@see AudioDeviceManager
|
||||
|
||||
@tags{Audio}
|
||||
*/
|
||||
class JUCE_API AudioDeviceSelectorComponent : public Component,
|
||||
private ChangeListener,
|
||||
private Timer
|
||||
{
|
||||
public:
|
||||
//==============================================================================
|
||||
/** Creates the component.
|
||||
|
||||
If your app needs only output channels, you might ask for a maximum of 0 input
|
||||
channels, and the component won't display any options for choosing the input
|
||||
channels. And likewise if you're doing an input-only app.
|
||||
|
||||
@param deviceManager the device manager that this component should control
|
||||
@param minAudioInputChannels the minimum number of audio input channels that the application needs
|
||||
@param maxAudioInputChannels the maximum number of audio input channels that the application needs
|
||||
@param minAudioOutputChannels the minimum number of audio output channels that the application needs
|
||||
@param maxAudioOutputChannels the maximum number of audio output channels that the application needs
|
||||
@param showMidiInputOptions if true, the component will allow the user to select which midi inputs are enabled
|
||||
@param showMidiOutputSelector if true, the component will let the user choose a default midi output device
|
||||
@param showChannelsAsStereoPairs if true, channels will be treated as pairs; if false, channels will be
|
||||
treated as a set of separate mono channels.
|
||||
@param hideAdvancedOptionsWithButton if true, only the minimum amount of UI components
|
||||
are shown, with an "advanced" button that shows the rest of them
|
||||
*/
|
||||
AudioDeviceSelectorComponent (AudioDeviceManager& deviceManager,
|
||||
int minAudioInputChannels,
|
||||
int maxAudioInputChannels,
|
||||
int minAudioOutputChannels,
|
||||
int maxAudioOutputChannels,
|
||||
bool showMidiInputOptions,
|
||||
bool showMidiOutputSelector,
|
||||
bool showChannelsAsStereoPairs,
|
||||
bool hideAdvancedOptionsWithButton);
|
||||
|
||||
/** Destructor */
|
||||
~AudioDeviceSelectorComponent() override;
|
||||
|
||||
/** The device manager that this component is controlling */
|
||||
AudioDeviceManager& deviceManager;
|
||||
|
||||
/** Sets the standard height used for items in the panel. */
|
||||
void setItemHeight (int itemHeight);
|
||||
|
||||
/** Returns the standard height used for items in the panel. */
|
||||
int getItemHeight() const noexcept { return itemHeight; }
|
||||
|
||||
/** Returns the ListBox that's being used to show the midi inputs, or nullptr if there isn't one. */
|
||||
ListBox* getMidiInputSelectorListBox() const noexcept;
|
||||
|
||||
//==============================================================================
|
||||
/** @internal */
|
||||
void resized() override;
|
||||
|
||||
private:
|
||||
//==============================================================================
|
||||
void timerCallback() override;
|
||||
void handleBluetoothButton();
|
||||
void updateDeviceType();
|
||||
void updateMidiOutput();
|
||||
void changeListenerCallback (ChangeBroadcaster*) override;
|
||||
void updateAllControls();
|
||||
|
||||
std::unique_ptr<ComboBox> deviceTypeDropDown;
|
||||
std::unique_ptr<Label> deviceTypeDropDownLabel;
|
||||
std::unique_ptr<Component> audioDeviceSettingsComp;
|
||||
String audioDeviceSettingsCompType;
|
||||
int itemHeight = 0;
|
||||
const int minOutputChannels, maxOutputChannels, minInputChannels, maxInputChannels;
|
||||
const bool showChannelsAsStereoPairs;
|
||||
const bool hideAdvancedOptionsWithButton;
|
||||
|
||||
class MidiInputSelectorComponentListBox;
|
||||
Array<MidiDeviceInfo> currentMidiOutputs;
|
||||
std::unique_ptr<MidiInputSelectorComponentListBox> midiInputsList;
|
||||
std::unique_ptr<ComboBox> midiOutputSelector;
|
||||
std::unique_ptr<Label> midiInputsLabel, midiOutputLabel;
|
||||
std::unique_ptr<TextButton> bluetoothButton;
|
||||
|
||||
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioDeviceSelectorComponent)
|
||||
};
|
||||
|
||||
} // namespace juce
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE library.
|
||||
Copyright (c) 2022 - Raw Material Software Limited
|
||||
|
||||
JUCE is an open source library subject to commercial or open-source
|
||||
licensing.
|
||||
|
||||
By using JUCE, you agree to the terms of both the JUCE 7 End-User License
|
||||
Agreement and JUCE Privacy Policy.
|
||||
|
||||
End User License Agreement: www.juce.com/juce-7-licence
|
||||
Privacy Policy: www.juce.com/juce-privacy-policy
|
||||
|
||||
Or: You may also use this code under the terms of the GPL v3 (see
|
||||
www.gnu.org/licenses).
|
||||
|
||||
JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
|
||||
EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
|
||||
DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
//==============================================================================
|
||||
/**
|
||||
A component containing controls to let the user change the audio settings of
|
||||
an AudioDeviceManager object.
|
||||
|
||||
Very easy to use - just create one of these and show it to the user.
|
||||
|
||||
@see AudioDeviceManager
|
||||
|
||||
@tags{Audio}
|
||||
*/
|
||||
class JUCE_API AudioDeviceSelectorComponent : public Component,
|
||||
private ChangeListener
|
||||
{
|
||||
public:
|
||||
//==============================================================================
|
||||
/** Creates the component.
|
||||
|
||||
If your app needs only output channels, you might ask for a maximum of 0 input
|
||||
channels, and the component won't display any options for choosing the input
|
||||
channels. And likewise if you're doing an input-only app.
|
||||
|
||||
@param deviceManager the device manager that this component should control
|
||||
@param minAudioInputChannels the minimum number of audio input channels that the application needs
|
||||
@param maxAudioInputChannels the maximum number of audio input channels that the application needs
|
||||
@param minAudioOutputChannels the minimum number of audio output channels that the application needs
|
||||
@param maxAudioOutputChannels the maximum number of audio output channels that the application needs
|
||||
@param showMidiInputOptions if true, the component will allow the user to select which midi inputs are enabled
|
||||
@param showMidiOutputSelector if true, the component will let the user choose a default midi output device
|
||||
@param showChannelsAsStereoPairs if true, channels will be treated as pairs; if false, channels will be
|
||||
treated as a set of separate mono channels.
|
||||
@param hideAdvancedOptionsWithButton if true, only the minimum amount of UI components
|
||||
are shown, with an "advanced" button that shows the rest of them
|
||||
*/
|
||||
AudioDeviceSelectorComponent (AudioDeviceManager& deviceManager,
|
||||
int minAudioInputChannels,
|
||||
int maxAudioInputChannels,
|
||||
int minAudioOutputChannels,
|
||||
int maxAudioOutputChannels,
|
||||
bool showMidiInputOptions,
|
||||
bool showMidiOutputSelector,
|
||||
bool showChannelsAsStereoPairs,
|
||||
bool hideAdvancedOptionsWithButton);
|
||||
|
||||
/** Destructor */
|
||||
~AudioDeviceSelectorComponent() override;
|
||||
|
||||
/** The device manager that this component is controlling */
|
||||
AudioDeviceManager& deviceManager;
|
||||
|
||||
/** Sets the standard height used for items in the panel. */
|
||||
void setItemHeight (int itemHeight);
|
||||
|
||||
/** Returns the standard height used for items in the panel. */
|
||||
int getItemHeight() const noexcept { return itemHeight; }
|
||||
|
||||
/** Returns the ListBox that's being used to show the midi inputs, or nullptr if there isn't one. */
|
||||
ListBox* getMidiInputSelectorListBox() const noexcept;
|
||||
|
||||
//==============================================================================
|
||||
/** @internal */
|
||||
void resized() override;
|
||||
|
||||
private:
|
||||
//==============================================================================
|
||||
void handleBluetoothButton();
|
||||
void updateDeviceType();
|
||||
void updateMidiOutput();
|
||||
void changeListenerCallback (ChangeBroadcaster*) override;
|
||||
void updateAllControls();
|
||||
|
||||
std::unique_ptr<ComboBox> deviceTypeDropDown;
|
||||
std::unique_ptr<Label> deviceTypeDropDownLabel;
|
||||
std::unique_ptr<Component> audioDeviceSettingsComp;
|
||||
String audioDeviceSettingsCompType;
|
||||
int itemHeight = 0;
|
||||
const int minOutputChannels, maxOutputChannels, minInputChannels, maxInputChannels;
|
||||
const bool showChannelsAsStereoPairs;
|
||||
const bool hideAdvancedOptionsWithButton;
|
||||
|
||||
class MidiInputSelectorComponentListBox;
|
||||
Array<MidiDeviceInfo> currentMidiOutputs;
|
||||
std::unique_ptr<MidiInputSelectorComponentListBox> midiInputsList;
|
||||
std::unique_ptr<ComboBox> midiOutputSelector;
|
||||
std::unique_ptr<Label> midiInputsLabel, midiOutputLabel;
|
||||
std::unique_ptr<TextButton> bluetoothButton;
|
||||
|
||||
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioDeviceSelectorComponent)
|
||||
};
|
||||
|
||||
} // namespace juce
|
||||
|
File diff suppressed because it is too large
Load Diff
@ -1,222 +1,222 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE library.
|
||||
Copyright (c) 2020 - Raw Material Software Limited
|
||||
|
||||
JUCE is an open source library subject to commercial or open-source
|
||||
licensing.
|
||||
|
||||
By using JUCE, you agree to the terms of both the JUCE 6 End-User License
|
||||
Agreement and JUCE Privacy Policy (both effective as of the 16th June 2020).
|
||||
|
||||
End User License Agreement: www.juce.com/juce-6-licence
|
||||
Privacy Policy: www.juce.com/juce-privacy-policy
|
||||
|
||||
Or: You may also use this code under the terms of the GPL v3 (see
|
||||
www.gnu.org/licenses).
|
||||
|
||||
JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
|
||||
EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
|
||||
DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
//==============================================================================
|
||||
/**
|
||||
Makes it easy to quickly draw scaled views of the waveform shape of an
|
||||
audio file.
|
||||
|
||||
To use this class, just create an AudioThumbnail class for the file you want
|
||||
to draw, call setSource to tell it which file or resource to use, then call
|
||||
drawChannel() to draw it.
|
||||
|
||||
The class will asynchronously scan the wavefile to create its scaled-down view,
|
||||
so you should make your UI repaint itself as this data comes in. To do this, the
|
||||
AudioThumbnail is a ChangeBroadcaster, and will broadcast a message when its
|
||||
listeners should repaint themselves.
|
||||
|
||||
The thumbnail stores an internal low-res version of the wave data, and this can
|
||||
be loaded and saved to avoid having to scan the file again.
|
||||
|
||||
@see AudioThumbnailCache, AudioThumbnailBase
|
||||
|
||||
@tags{Audio}
|
||||
*/
|
||||
class JUCE_API AudioThumbnail : public AudioThumbnailBase
|
||||
{
|
||||
public:
|
||||
//==============================================================================
|
||||
/** Creates an audio thumbnail.
|
||||
|
||||
@param sourceSamplesPerThumbnailSample when creating a stored, low-res version
|
||||
of the audio data, this is the scale at which it should be done. (This
|
||||
number is the number of original samples that will be averaged for each
|
||||
low-res sample)
|
||||
@param formatManagerToUse the audio format manager that is used to open the file
|
||||
@param cacheToUse an instance of an AudioThumbnailCache - this provides a background
|
||||
thread and storage that is used to by the thumbnail, and the cache
|
||||
object can be shared between multiple thumbnails
|
||||
*/
|
||||
AudioThumbnail (int sourceSamplesPerThumbnailSample,
|
||||
AudioFormatManager& formatManagerToUse,
|
||||
AudioThumbnailCache& cacheToUse);
|
||||
|
||||
/** Destructor. */
|
||||
~AudioThumbnail() override;
|
||||
|
||||
//==============================================================================
|
||||
/** Clears and resets the thumbnail. */
|
||||
void clear() override;
|
||||
|
||||
/** Specifies the file or stream that contains the audio file.
|
||||
|
||||
For a file, just call
|
||||
@code
|
||||
setSource (new FileInputSource (file))
|
||||
@endcode
|
||||
|
||||
You can pass a nullptr in here to clear the thumbnail.
|
||||
The source that is passed in will be deleted by this object when it is no longer needed.
|
||||
@returns true if the source could be opened as a valid audio file, false if this failed for
|
||||
some reason.
|
||||
*/
|
||||
bool setSource (InputSource* newSource) override;
|
||||
|
||||
/** Gives the thumbnail an AudioFormatReader to use directly.
|
||||
This will start parsing the audio in a background thread (unless the hash code
|
||||
can be looked-up successfully in the thumbnail cache). Note that the reader
|
||||
object will be held by the thumbnail and deleted later when no longer needed.
|
||||
The thumbnail will actually keep hold of this reader until you clear the thumbnail
|
||||
or change the input source, so the file will be held open for all this time. If
|
||||
you don't want the thumbnail to keep a file handle open continuously, you
|
||||
should use the setSource() method instead, which will only open the file when
|
||||
it needs to.
|
||||
*/
|
||||
void setReader (AudioFormatReader* newReader, int64 hashCode) override;
|
||||
|
||||
/** Resets the thumbnail, ready for adding data with the specified format.
|
||||
If you're going to generate a thumbnail yourself, call this before using addBlock()
|
||||
to add the data.
|
||||
*/
|
||||
void reset (int numChannels, double sampleRate, int64 totalSamplesInSource = 0) override;
|
||||
|
||||
/** Adds a block of level data to the thumbnail.
|
||||
Call reset() before using this, to tell the thumbnail about the data format.
|
||||
*/
|
||||
void addBlock (int64 sampleNumberInSource, const AudioBuffer<float>& newData,
|
||||
int startOffsetInBuffer, int numSamples) override;
|
||||
|
||||
//==============================================================================
|
||||
/** Reloads the low res thumbnail data from an input stream.
|
||||
|
||||
This is not an audio file stream! It takes a stream of thumbnail data that would
|
||||
previously have been created by the saveTo() method.
|
||||
@see saveTo
|
||||
*/
|
||||
bool loadFrom (InputStream& input) override;
|
||||
|
||||
/** Saves the low res thumbnail data to an output stream.
|
||||
|
||||
The data that is written can later be reloaded using loadFrom().
|
||||
@see loadFrom
|
||||
*/
|
||||
void saveTo (OutputStream& output) const override;
|
||||
|
||||
//==============================================================================
|
||||
/** Returns the number of channels in the file. */
|
||||
int getNumChannels() const noexcept override;
|
||||
|
||||
/** Returns the length of the audio file, in seconds. */
|
||||
double getTotalLength() const noexcept override;
|
||||
|
||||
/** Draws the waveform for a channel.
|
||||
|
||||
The waveform will be drawn within the specified rectangle, where startTime
|
||||
and endTime specify the times within the audio file that should be positioned
|
||||
at the left and right edges of the rectangle.
|
||||
|
||||
The waveform will be scaled vertically so that a full-volume sample will fill
|
||||
the rectangle vertically, but you can also specify an extra vertical scale factor
|
||||
with the verticalZoomFactor parameter.
|
||||
*/
|
||||
void drawChannel (Graphics& g,
|
||||
const Rectangle<int>& area,
|
||||
double startTimeSeconds,
|
||||
double endTimeSeconds,
|
||||
int channelNum,
|
||||
float verticalZoomFactor) override;
|
||||
|
||||
/** Draws the waveforms for all channels in the thumbnail.
|
||||
|
||||
This will call drawChannel() to render each of the thumbnail's channels, stacked
|
||||
above each other within the specified area.
|
||||
|
||||
@see drawChannel
|
||||
*/
|
||||
void drawChannels (Graphics& g,
|
||||
const Rectangle<int>& area,
|
||||
double startTimeSeconds,
|
||||
double endTimeSeconds,
|
||||
float verticalZoomFactor) override;
|
||||
|
||||
/** Returns true if the low res preview is fully generated. */
|
||||
bool isFullyLoaded() const noexcept override;
|
||||
|
||||
/** Returns a value between 0 and 1 to indicate the progress towards loading the entire file. */
|
||||
double getProportionComplete() const noexcept;
|
||||
|
||||
/** Returns the number of samples that have been set in the thumbnail. */
|
||||
int64 getNumSamplesFinished() const noexcept override;
|
||||
|
||||
/** Returns the highest level in the thumbnail.
|
||||
Note that because the thumb only stores low-resolution data, this isn't
|
||||
an accurate representation of the highest value, it's only a rough approximation.
|
||||
*/
|
||||
float getApproximatePeak() const override;
|
||||
|
||||
/** Reads the approximate min and max levels from a section of the thumbnail.
|
||||
The lowest and highest samples are returned in minValue and maxValue, but obviously
|
||||
because the thumb only stores low-resolution data, these numbers will only be a rough
|
||||
approximation of the true values.
|
||||
*/
|
||||
void getApproximateMinMax (double startTime, double endTime, int channelIndex,
|
||||
float& minValue, float& maxValue) const noexcept override;
|
||||
|
||||
/** Returns the hash code that was set by setSource() or setReader(). */
|
||||
int64 getHashCode() const override;
|
||||
|
||||
private:
|
||||
//==============================================================================
|
||||
AudioFormatManager& formatManagerToUse;
|
||||
AudioThumbnailCache& cache;
|
||||
|
||||
class LevelDataSource;
|
||||
struct MinMaxValue;
|
||||
class ThumbData;
|
||||
class CachedWindow;
|
||||
|
||||
std::unique_ptr<LevelDataSource> source;
|
||||
std::unique_ptr<CachedWindow> window;
|
||||
OwnedArray<ThumbData> channels;
|
||||
|
||||
int32 samplesPerThumbSample = 0;
|
||||
std::atomic<int64> totalSamples { 0 };
|
||||
int64 numSamplesFinished = 0;
|
||||
int32 numChannels = 0;
|
||||
double sampleRate = 0;
|
||||
CriticalSection lock;
|
||||
|
||||
void clearChannelData();
|
||||
bool setDataSource (LevelDataSource* newSource);
|
||||
void setLevels (const MinMaxValue* const* values, int thumbIndex, int numChans, int numValues);
|
||||
void createChannels (int length);
|
||||
|
||||
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioThumbnail)
|
||||
};
|
||||
|
||||
} // namespace juce
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE library.
|
||||
Copyright (c) 2022 - Raw Material Software Limited
|
||||
|
||||
JUCE is an open source library subject to commercial or open-source
|
||||
licensing.
|
||||
|
||||
By using JUCE, you agree to the terms of both the JUCE 7 End-User License
|
||||
Agreement and JUCE Privacy Policy.
|
||||
|
||||
End User License Agreement: www.juce.com/juce-7-licence
|
||||
Privacy Policy: www.juce.com/juce-privacy-policy
|
||||
|
||||
Or: You may also use this code under the terms of the GPL v3 (see
|
||||
www.gnu.org/licenses).
|
||||
|
||||
JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
|
||||
EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
|
||||
DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
//==============================================================================
|
||||
/**
|
||||
Makes it easy to quickly draw scaled views of the waveform shape of an
|
||||
audio file.
|
||||
|
||||
To use this class, just create an AudioThumbnail class for the file you want
|
||||
to draw, call setSource to tell it which file or resource to use, then call
|
||||
drawChannel() to draw it.
|
||||
|
||||
The class will asynchronously scan the wavefile to create its scaled-down view,
|
||||
so you should make your UI repaint itself as this data comes in. To do this, the
|
||||
AudioThumbnail is a ChangeBroadcaster, and will broadcast a message when its
|
||||
listeners should repaint themselves.
|
||||
|
||||
The thumbnail stores an internal low-res version of the wave data, and this can
|
||||
be loaded and saved to avoid having to scan the file again.
|
||||
|
||||
@see AudioThumbnailCache, AudioThumbnailBase
|
||||
|
||||
@tags{Audio}
|
||||
*/
|
||||
class JUCE_API AudioThumbnail : public AudioThumbnailBase
|
||||
{
|
||||
public:
|
||||
//==============================================================================
|
||||
/** Creates an audio thumbnail.
|
||||
|
||||
@param sourceSamplesPerThumbnailSample when creating a stored, low-res version
|
||||
of the audio data, this is the scale at which it should be done. (This
|
||||
number is the number of original samples that will be averaged for each
|
||||
low-res sample)
|
||||
@param formatManagerToUse the audio format manager that is used to open the file
|
||||
@param cacheToUse an instance of an AudioThumbnailCache - this provides a background
|
||||
thread and storage that is used to by the thumbnail, and the cache
|
||||
object can be shared between multiple thumbnails
|
||||
*/
|
||||
AudioThumbnail (int sourceSamplesPerThumbnailSample,
|
||||
AudioFormatManager& formatManagerToUse,
|
||||
AudioThumbnailCache& cacheToUse);
|
||||
|
||||
/** Destructor. */
|
||||
~AudioThumbnail() override;
|
||||
|
||||
//==============================================================================
|
||||
/** Clears and resets the thumbnail. */
|
||||
void clear() override;
|
||||
|
||||
/** Specifies the file or stream that contains the audio file.
|
||||
|
||||
For a file, just call
|
||||
@code
|
||||
setSource (new FileInputSource (file))
|
||||
@endcode
|
||||
|
||||
You can pass a nullptr in here to clear the thumbnail.
|
||||
The source that is passed in will be deleted by this object when it is no longer needed.
|
||||
@returns true if the source could be opened as a valid audio file, false if this failed for
|
||||
some reason.
|
||||
*/
|
||||
bool setSource (InputSource* newSource) override;
|
||||
|
||||
/** Gives the thumbnail an AudioFormatReader to use directly.
|
||||
This will start parsing the audio in a background thread (unless the hash code
|
||||
can be looked-up successfully in the thumbnail cache). Note that the reader
|
||||
object will be held by the thumbnail and deleted later when no longer needed.
|
||||
The thumbnail will actually keep hold of this reader until you clear the thumbnail
|
||||
or change the input source, so the file will be held open for all this time. If
|
||||
you don't want the thumbnail to keep a file handle open continuously, you
|
||||
should use the setSource() method instead, which will only open the file when
|
||||
it needs to.
|
||||
*/
|
||||
void setReader (AudioFormatReader* newReader, int64 hashCode) override;
|
||||
|
||||
/** Resets the thumbnail, ready for adding data with the specified format.
|
||||
If you're going to generate a thumbnail yourself, call this before using addBlock()
|
||||
to add the data.
|
||||
*/
|
||||
void reset (int numChannels, double sampleRate, int64 totalSamplesInSource = 0) override;
|
||||
|
||||
/** Adds a block of level data to the thumbnail.
|
||||
Call reset() before using this, to tell the thumbnail about the data format.
|
||||
*/
|
||||
void addBlock (int64 sampleNumberInSource, const AudioBuffer<float>& newData,
|
||||
int startOffsetInBuffer, int numSamples) override;
|
||||
|
||||
//==============================================================================
|
||||
/** Reloads the low res thumbnail data from an input stream.
|
||||
|
||||
This is not an audio file stream! It takes a stream of thumbnail data that would
|
||||
previously have been created by the saveTo() method.
|
||||
@see saveTo
|
||||
*/
|
||||
bool loadFrom (InputStream& input) override;
|
||||
|
||||
/** Saves the low res thumbnail data to an output stream.
|
||||
|
||||
The data that is written can later be reloaded using loadFrom().
|
||||
@see loadFrom
|
||||
*/
|
||||
void saveTo (OutputStream& output) const override;
|
||||
|
||||
//==============================================================================
|
||||
/** Returns the number of channels in the file. */
|
||||
int getNumChannels() const noexcept override;
|
||||
|
||||
/** Returns the length of the audio file, in seconds. */
|
||||
double getTotalLength() const noexcept override;
|
||||
|
||||
/** Draws the waveform for a channel.
|
||||
|
||||
The waveform will be drawn within the specified rectangle, where startTime
|
||||
and endTime specify the times within the audio file that should be positioned
|
||||
at the left and right edges of the rectangle.
|
||||
|
||||
The waveform will be scaled vertically so that a full-volume sample will fill
|
||||
the rectangle vertically, but you can also specify an extra vertical scale factor
|
||||
with the verticalZoomFactor parameter.
|
||||
*/
|
||||
void drawChannel (Graphics& g,
|
||||
const Rectangle<int>& area,
|
||||
double startTimeSeconds,
|
||||
double endTimeSeconds,
|
||||
int channelNum,
|
||||
float verticalZoomFactor) override;
|
||||
|
||||
/** Draws the waveforms for all channels in the thumbnail.
|
||||
|
||||
This will call drawChannel() to render each of the thumbnail's channels, stacked
|
||||
above each other within the specified area.
|
||||
|
||||
@see drawChannel
|
||||
*/
|
||||
void drawChannels (Graphics& g,
|
||||
const Rectangle<int>& area,
|
||||
double startTimeSeconds,
|
||||
double endTimeSeconds,
|
||||
float verticalZoomFactor) override;
|
||||
|
||||
/** Returns true if the low res preview is fully generated. */
|
||||
bool isFullyLoaded() const noexcept override;
|
||||
|
||||
/** Returns a value between 0 and 1 to indicate the progress towards loading the entire file. */
|
||||
double getProportionComplete() const noexcept;
|
||||
|
||||
/** Returns the number of samples that have been set in the thumbnail. */
|
||||
int64 getNumSamplesFinished() const noexcept override;
|
||||
|
||||
/** Returns the highest level in the thumbnail.
|
||||
Note that because the thumb only stores low-resolution data, this isn't
|
||||
an accurate representation of the highest value, it's only a rough approximation.
|
||||
*/
|
||||
float getApproximatePeak() const override;
|
||||
|
||||
/** Reads the approximate min and max levels from a section of the thumbnail.
|
||||
The lowest and highest samples are returned in minValue and maxValue, but obviously
|
||||
because the thumb only stores low-resolution data, these numbers will only be a rough
|
||||
approximation of the true values.
|
||||
*/
|
||||
void getApproximateMinMax (double startTime, double endTime, int channelIndex,
|
||||
float& minValue, float& maxValue) const noexcept override;
|
||||
|
||||
/** Returns the hash code that was set by setSource() or setReader(). */
|
||||
int64 getHashCode() const override;
|
||||
|
||||
private:
|
||||
//==============================================================================
|
||||
AudioFormatManager& formatManagerToUse;
|
||||
AudioThumbnailCache& cache;
|
||||
|
||||
class LevelDataSource;
|
||||
struct MinMaxValue;
|
||||
class ThumbData;
|
||||
class CachedWindow;
|
||||
|
||||
std::unique_ptr<LevelDataSource> source;
|
||||
std::unique_ptr<CachedWindow> window;
|
||||
OwnedArray<ThumbData> channels;
|
||||
|
||||
int32 samplesPerThumbSample = 0;
|
||||
int64 totalSamples { 0 };
|
||||
int64 numSamplesFinished = 0;
|
||||
int32 numChannels = 0;
|
||||
double sampleRate = 0;
|
||||
CriticalSection lock;
|
||||
|
||||
void clearChannelData();
|
||||
bool setDataSource (LevelDataSource* newSource);
|
||||
void setLevels (const MinMaxValue* const* values, int thumbIndex, int numChans, int numValues);
|
||||
void createChannels (int length);
|
||||
|
||||
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioThumbnail)
|
||||
};
|
||||
|
||||
} // namespace juce
|
||||
|
@ -1,158 +1,158 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE library.
|
||||
Copyright (c) 2020 - Raw Material Software Limited
|
||||
|
||||
JUCE is an open source library subject to commercial or open-source
|
||||
licensing.
|
||||
|
||||
By using JUCE, you agree to the terms of both the JUCE 6 End-User License
|
||||
Agreement and JUCE Privacy Policy (both effective as of the 16th June 2020).
|
||||
|
||||
End User License Agreement: www.juce.com/juce-6-licence
|
||||
Privacy Policy: www.juce.com/juce-privacy-policy
|
||||
|
||||
Or: You may also use this code under the terms of the GPL v3 (see
|
||||
www.gnu.org/licenses).
|
||||
|
||||
JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
|
||||
EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
|
||||
DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
class AudioThumbnailCache;
|
||||
|
||||
//==============================================================================
|
||||
/**
|
||||
Provides a base for classes that can store and draw scaled views of an
|
||||
audio waveform.
|
||||
|
||||
Typically, you'll want to use the derived class AudioThumbnail, which provides
|
||||
a concrete implementation.
|
||||
|
||||
@see AudioThumbnail, AudioThumbnailCache
|
||||
|
||||
@tags{Audio}
|
||||
*/
|
||||
class JUCE_API AudioThumbnailBase : public ChangeBroadcaster,
|
||||
public AudioFormatWriter::ThreadedWriter::IncomingDataReceiver
|
||||
{
|
||||
public:
|
||||
//==============================================================================
|
||||
AudioThumbnailBase() = default;
|
||||
~AudioThumbnailBase() override = default;
|
||||
|
||||
//==============================================================================
|
||||
/** Clears and resets the thumbnail. */
|
||||
virtual void clear() = 0;
|
||||
|
||||
/** Specifies the file or stream that contains the audio file.
|
||||
|
||||
For a file, just call
|
||||
@code
|
||||
setSource (new FileInputSource (file))
|
||||
@endcode
|
||||
|
||||
You can pass a nullptr in here to clear the thumbnail.
|
||||
The source that is passed in will be deleted by this object when it is no longer needed.
|
||||
@returns true if the source could be opened as a valid audio file, false if this failed for
|
||||
some reason.
|
||||
*/
|
||||
virtual bool setSource (InputSource* newSource) = 0;
|
||||
|
||||
/** Gives the thumbnail an AudioFormatReader to use directly.
|
||||
This will start parsing the audio in a background thread (unless the hash code
|
||||
can be looked-up successfully in the thumbnail cache). Note that the reader
|
||||
object will be held by the thumbnail and deleted later when no longer needed.
|
||||
The thumbnail will actually keep hold of this reader until you clear the thumbnail
|
||||
or change the input source, so the file will be held open for all this time. If
|
||||
you don't want the thumbnail to keep a file handle open continuously, you
|
||||
should use the setSource() method instead, which will only open the file when
|
||||
it needs to.
|
||||
*/
|
||||
virtual void setReader (AudioFormatReader* newReader, int64 hashCode) = 0;
|
||||
|
||||
//==============================================================================
|
||||
/** Reloads the low res thumbnail data from an input stream.
|
||||
|
||||
This is not an audio file stream! It takes a stream of thumbnail data that would
|
||||
previously have been created by the saveTo() method.
|
||||
@see saveTo
|
||||
*/
|
||||
virtual bool loadFrom (InputStream& input) = 0;
|
||||
|
||||
/** Saves the low res thumbnail data to an output stream.
|
||||
|
||||
The data that is written can later be reloaded using loadFrom().
|
||||
@see loadFrom
|
||||
*/
|
||||
virtual void saveTo (OutputStream& output) const = 0;
|
||||
|
||||
//==============================================================================
|
||||
/** Returns the number of channels in the file. */
|
||||
virtual int getNumChannels() const noexcept = 0;
|
||||
|
||||
/** Returns the length of the audio file, in seconds. */
|
||||
virtual double getTotalLength() const noexcept = 0;
|
||||
|
||||
/** Draws the waveform for a channel.
|
||||
|
||||
The waveform will be drawn within the specified rectangle, where startTime
|
||||
and endTime specify the times within the audio file that should be positioned
|
||||
at the left and right edges of the rectangle.
|
||||
|
||||
The waveform will be scaled vertically so that a full-volume sample will fill
|
||||
the rectangle vertically, but you can also specify an extra vertical scale factor
|
||||
with the verticalZoomFactor parameter.
|
||||
*/
|
||||
virtual void drawChannel (Graphics& g,
|
||||
const Rectangle<int>& area,
|
||||
double startTimeSeconds,
|
||||
double endTimeSeconds,
|
||||
int channelNum,
|
||||
float verticalZoomFactor) = 0;
|
||||
|
||||
/** Draws the waveforms for all channels in the thumbnail.
|
||||
|
||||
This will call drawChannel() to render each of the thumbnail's channels, stacked
|
||||
above each other within the specified area.
|
||||
|
||||
@see drawChannel
|
||||
*/
|
||||
virtual void drawChannels (Graphics& g,
|
||||
const Rectangle<int>& area,
|
||||
double startTimeSeconds,
|
||||
double endTimeSeconds,
|
||||
float verticalZoomFactor) = 0;
|
||||
|
||||
/** Returns true if the low res preview is fully generated. */
|
||||
virtual bool isFullyLoaded() const noexcept = 0;
|
||||
|
||||
/** Returns the number of samples that have been set in the thumbnail. */
|
||||
virtual int64 getNumSamplesFinished() const noexcept = 0;
|
||||
|
||||
/** Returns the highest level in the thumbnail.
|
||||
Note that because the thumb only stores low-resolution data, this isn't
|
||||
an accurate representation of the highest value, it's only a rough approximation.
|
||||
*/
|
||||
virtual float getApproximatePeak() const = 0;
|
||||
|
||||
/** Reads the approximate min and max levels from a section of the thumbnail.
|
||||
The lowest and highest samples are returned in minValue and maxValue, but obviously
|
||||
because the thumb only stores low-resolution data, these numbers will only be a rough
|
||||
approximation of the true values.
|
||||
*/
|
||||
virtual void getApproximateMinMax (double startTime, double endTime, int channelIndex,
|
||||
float& minValue, float& maxValue) const noexcept = 0;
|
||||
|
||||
/** Returns the hash code that was set by setSource() or setReader(). */
|
||||
virtual int64 getHashCode() const = 0;
|
||||
};
|
||||
|
||||
} // namespace juce
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE library.
|
||||
Copyright (c) 2022 - Raw Material Software Limited
|
||||
|
||||
JUCE is an open source library subject to commercial or open-source
|
||||
licensing.
|
||||
|
||||
By using JUCE, you agree to the terms of both the JUCE 7 End-User License
|
||||
Agreement and JUCE Privacy Policy.
|
||||
|
||||
End User License Agreement: www.juce.com/juce-7-licence
|
||||
Privacy Policy: www.juce.com/juce-privacy-policy
|
||||
|
||||
Or: You may also use this code under the terms of the GPL v3 (see
|
||||
www.gnu.org/licenses).
|
||||
|
||||
JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
|
||||
EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
|
||||
DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
class AudioThumbnailCache;
|
||||
|
||||
//==============================================================================
|
||||
/**
|
||||
Provides a base for classes that can store and draw scaled views of an
|
||||
audio waveform.
|
||||
|
||||
Typically, you'll want to use the derived class AudioThumbnail, which provides
|
||||
a concrete implementation.
|
||||
|
||||
@see AudioThumbnail, AudioThumbnailCache
|
||||
|
||||
@tags{Audio}
|
||||
*/
|
||||
class JUCE_API AudioThumbnailBase : public ChangeBroadcaster,
|
||||
public AudioFormatWriter::ThreadedWriter::IncomingDataReceiver
|
||||
{
|
||||
public:
|
||||
//==============================================================================
|
||||
AudioThumbnailBase() = default;
|
||||
~AudioThumbnailBase() override = default;
|
||||
|
||||
//==============================================================================
|
||||
/** Clears and resets the thumbnail. */
|
||||
virtual void clear() = 0;
|
||||
|
||||
/** Specifies the file or stream that contains the audio file.
|
||||
|
||||
For a file, just call
|
||||
@code
|
||||
setSource (new FileInputSource (file))
|
||||
@endcode
|
||||
|
||||
You can pass a nullptr in here to clear the thumbnail.
|
||||
The source that is passed in will be deleted by this object when it is no longer needed.
|
||||
@returns true if the source could be opened as a valid audio file, false if this failed for
|
||||
some reason.
|
||||
*/
|
||||
virtual bool setSource (InputSource* newSource) = 0;
|
||||
|
||||
/** Gives the thumbnail an AudioFormatReader to use directly.
|
||||
This will start parsing the audio in a background thread (unless the hash code
|
||||
can be looked-up successfully in the thumbnail cache). Note that the reader
|
||||
object will be held by the thumbnail and deleted later when no longer needed.
|
||||
The thumbnail will actually keep hold of this reader until you clear the thumbnail
|
||||
or change the input source, so the file will be held open for all this time. If
|
||||
you don't want the thumbnail to keep a file handle open continuously, you
|
||||
should use the setSource() method instead, which will only open the file when
|
||||
it needs to.
|
||||
*/
|
||||
virtual void setReader (AudioFormatReader* newReader, int64 hashCode) = 0;
|
||||
|
||||
//==============================================================================
|
||||
/** Reloads the low res thumbnail data from an input stream.
|
||||
|
||||
This is not an audio file stream! It takes a stream of thumbnail data that would
|
||||
previously have been created by the saveTo() method.
|
||||
@see saveTo
|
||||
*/
|
||||
virtual bool loadFrom (InputStream& input) = 0;
|
||||
|
||||
/** Saves the low res thumbnail data to an output stream.
|
||||
|
||||
The data that is written can later be reloaded using loadFrom().
|
||||
@see loadFrom
|
||||
*/
|
||||
virtual void saveTo (OutputStream& output) const = 0;
|
||||
|
||||
//==============================================================================
|
||||
/** Returns the number of channels in the file. */
|
||||
virtual int getNumChannels() const noexcept = 0;
|
||||
|
||||
/** Returns the length of the audio file, in seconds. */
|
||||
virtual double getTotalLength() const noexcept = 0;
|
||||
|
||||
/** Draws the waveform for a channel.
|
||||
|
||||
The waveform will be drawn within the specified rectangle, where startTime
|
||||
and endTime specify the times within the audio file that should be positioned
|
||||
at the left and right edges of the rectangle.
|
||||
|
||||
The waveform will be scaled vertically so that a full-volume sample will fill
|
||||
the rectangle vertically, but you can also specify an extra vertical scale factor
|
||||
with the verticalZoomFactor parameter.
|
||||
*/
|
||||
virtual void drawChannel (Graphics& g,
|
||||
const Rectangle<int>& area,
|
||||
double startTimeSeconds,
|
||||
double endTimeSeconds,
|
||||
int channelNum,
|
||||
float verticalZoomFactor) = 0;
|
||||
|
||||
/** Draws the waveforms for all channels in the thumbnail.
|
||||
|
||||
This will call drawChannel() to render each of the thumbnail's channels, stacked
|
||||
above each other within the specified area.
|
||||
|
||||
@see drawChannel
|
||||
*/
|
||||
virtual void drawChannels (Graphics& g,
|
||||
const Rectangle<int>& area,
|
||||
double startTimeSeconds,
|
||||
double endTimeSeconds,
|
||||
float verticalZoomFactor) = 0;
|
||||
|
||||
/** Returns true if the low res preview is fully generated. */
|
||||
virtual bool isFullyLoaded() const noexcept = 0;
|
||||
|
||||
/** Returns the number of samples that have been set in the thumbnail. */
|
||||
virtual int64 getNumSamplesFinished() const noexcept = 0;
|
||||
|
||||
/** Returns the highest level in the thumbnail.
|
||||
Note that because the thumb only stores low-resolution data, this isn't
|
||||
an accurate representation of the highest value, it's only a rough approximation.
|
||||
*/
|
||||
virtual float getApproximatePeak() const = 0;
|
||||
|
||||
/** Reads the approximate min and max levels from a section of the thumbnail.
|
||||
The lowest and highest samples are returned in minValue and maxValue, but obviously
|
||||
because the thumb only stores low-resolution data, these numbers will only be a rough
|
||||
approximation of the true values.
|
||||
*/
|
||||
virtual void getApproximateMinMax (double startTime, double endTime, int channelIndex,
|
||||
float& minValue, float& maxValue) const noexcept = 0;
|
||||
|
||||
/** Returns the hash code that was set by setSource() or setReader(). */
|
||||
virtual int64 getHashCode() const = 0;
|
||||
};
|
||||
|
||||
} // namespace juce
|
||||
|
@ -1,197 +1,197 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE library.
|
||||
Copyright (c) 2020 - Raw Material Software Limited
|
||||
|
||||
JUCE is an open source library subject to commercial or open-source
|
||||
licensing.
|
||||
|
||||
By using JUCE, you agree to the terms of both the JUCE 6 End-User License
|
||||
Agreement and JUCE Privacy Policy (both effective as of the 16th June 2020).
|
||||
|
||||
End User License Agreement: www.juce.com/juce-6-licence
|
||||
Privacy Policy: www.juce.com/juce-privacy-policy
|
||||
|
||||
Or: You may also use this code under the terms of the GPL v3 (see
|
||||
www.gnu.org/licenses).
|
||||
|
||||
JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
|
||||
EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
|
||||
DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
class AudioThumbnailCache::ThumbnailCacheEntry
|
||||
{
|
||||
public:
|
||||
ThumbnailCacheEntry (const int64 hashCode)
|
||||
: hash (hashCode),
|
||||
lastUsed (Time::getMillisecondCounter())
|
||||
{
|
||||
}
|
||||
|
||||
ThumbnailCacheEntry (InputStream& in)
|
||||
: hash (in.readInt64()),
|
||||
lastUsed (0)
|
||||
{
|
||||
const int64 len = in.readInt64();
|
||||
in.readIntoMemoryBlock (data, (ssize_t) len);
|
||||
}
|
||||
|
||||
void write (OutputStream& out)
|
||||
{
|
||||
out.writeInt64 (hash);
|
||||
out.writeInt64 ((int64) data.getSize());
|
||||
out << data;
|
||||
}
|
||||
|
||||
int64 hash;
|
||||
uint32 lastUsed;
|
||||
MemoryBlock data;
|
||||
|
||||
private:
|
||||
JUCE_LEAK_DETECTOR (ThumbnailCacheEntry)
|
||||
};
|
||||
|
||||
//==============================================================================
|
||||
AudioThumbnailCache::AudioThumbnailCache (const int maxNumThumbs)
|
||||
: thread ("thumb cache"),
|
||||
maxNumThumbsToStore (maxNumThumbs)
|
||||
{
|
||||
jassert (maxNumThumbsToStore > 0);
|
||||
thread.startThread (2);
|
||||
}
|
||||
|
||||
AudioThumbnailCache::~AudioThumbnailCache()
|
||||
{
|
||||
}
|
||||
|
||||
AudioThumbnailCache::ThumbnailCacheEntry* AudioThumbnailCache::findThumbFor (const int64 hash) const
|
||||
{
|
||||
for (int i = thumbs.size(); --i >= 0;)
|
||||
if (thumbs.getUnchecked(i)->hash == hash)
|
||||
return thumbs.getUnchecked(i);
|
||||
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
int AudioThumbnailCache::findOldestThumb() const
|
||||
{
|
||||
int oldest = 0;
|
||||
uint32 oldestTime = Time::getMillisecondCounter() + 1;
|
||||
|
||||
for (int i = thumbs.size(); --i >= 0;)
|
||||
{
|
||||
const ThumbnailCacheEntry* const te = thumbs.getUnchecked(i);
|
||||
|
||||
if (te->lastUsed < oldestTime)
|
||||
{
|
||||
oldest = i;
|
||||
oldestTime = te->lastUsed;
|
||||
}
|
||||
}
|
||||
|
||||
return oldest;
|
||||
}
|
||||
|
||||
bool AudioThumbnailCache::loadThumb (AudioThumbnailBase& thumb, const int64 hashCode)
|
||||
{
|
||||
const ScopedLock sl (lock);
|
||||
|
||||
if (ThumbnailCacheEntry* te = findThumbFor (hashCode))
|
||||
{
|
||||
te->lastUsed = Time::getMillisecondCounter();
|
||||
|
||||
MemoryInputStream in (te->data, false);
|
||||
thumb.loadFrom (in);
|
||||
return true;
|
||||
}
|
||||
|
||||
return loadNewThumb (thumb, hashCode);
|
||||
}
|
||||
|
||||
void AudioThumbnailCache::storeThumb (const AudioThumbnailBase& thumb,
|
||||
const int64 hashCode)
|
||||
{
|
||||
const ScopedLock sl (lock);
|
||||
ThumbnailCacheEntry* te = findThumbFor (hashCode);
|
||||
|
||||
if (te == nullptr)
|
||||
{
|
||||
te = new ThumbnailCacheEntry (hashCode);
|
||||
|
||||
if (thumbs.size() < maxNumThumbsToStore)
|
||||
thumbs.add (te);
|
||||
else
|
||||
thumbs.set (findOldestThumb(), te);
|
||||
}
|
||||
|
||||
{
|
||||
MemoryOutputStream out (te->data, false);
|
||||
thumb.saveTo (out);
|
||||
}
|
||||
|
||||
saveNewlyFinishedThumbnail (thumb, hashCode);
|
||||
}
|
||||
|
||||
void AudioThumbnailCache::clear()
|
||||
{
|
||||
const ScopedLock sl (lock);
|
||||
thumbs.clear();
|
||||
}
|
||||
|
||||
void AudioThumbnailCache::removeThumb (const int64 hashCode)
|
||||
{
|
||||
const ScopedLock sl (lock);
|
||||
|
||||
for (int i = thumbs.size(); --i >= 0;)
|
||||
if (thumbs.getUnchecked(i)->hash == hashCode)
|
||||
thumbs.remove (i);
|
||||
}
|
||||
|
||||
static int getThumbnailCacheFileMagicHeader() noexcept
|
||||
{
|
||||
return (int) ByteOrder::littleEndianInt ("ThmC");
|
||||
}
|
||||
|
||||
bool AudioThumbnailCache::readFromStream (InputStream& source)
|
||||
{
|
||||
if (source.readInt() != getThumbnailCacheFileMagicHeader())
|
||||
return false;
|
||||
|
||||
const ScopedLock sl (lock);
|
||||
clear();
|
||||
int numThumbnails = jmin (maxNumThumbsToStore, source.readInt());
|
||||
|
||||
while (--numThumbnails >= 0 && ! source.isExhausted())
|
||||
thumbs.add (new ThumbnailCacheEntry (source));
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
void AudioThumbnailCache::writeToStream (OutputStream& out)
|
||||
{
|
||||
const ScopedLock sl (lock);
|
||||
|
||||
out.writeInt (getThumbnailCacheFileMagicHeader());
|
||||
out.writeInt (thumbs.size());
|
||||
|
||||
for (int i = 0; i < thumbs.size(); ++i)
|
||||
thumbs.getUnchecked(i)->write (out);
|
||||
}
|
||||
|
||||
void AudioThumbnailCache::saveNewlyFinishedThumbnail (const AudioThumbnailBase&, int64)
|
||||
{
|
||||
}
|
||||
|
||||
bool AudioThumbnailCache::loadNewThumb (AudioThumbnailBase&, int64)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
} // namespace juce
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE library.
|
||||
Copyright (c) 2022 - Raw Material Software Limited
|
||||
|
||||
JUCE is an open source library subject to commercial or open-source
|
||||
licensing.
|
||||
|
||||
By using JUCE, you agree to the terms of both the JUCE 7 End-User License
|
||||
Agreement and JUCE Privacy Policy.
|
||||
|
||||
End User License Agreement: www.juce.com/juce-7-licence
|
||||
Privacy Policy: www.juce.com/juce-privacy-policy
|
||||
|
||||
Or: You may also use this code under the terms of the GPL v3 (see
|
||||
www.gnu.org/licenses).
|
||||
|
||||
JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
|
||||
EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
|
||||
DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
class AudioThumbnailCache::ThumbnailCacheEntry
|
||||
{
|
||||
public:
|
||||
ThumbnailCacheEntry (const int64 hashCode)
|
||||
: hash (hashCode),
|
||||
lastUsed (Time::getMillisecondCounter())
|
||||
{
|
||||
}
|
||||
|
||||
ThumbnailCacheEntry (InputStream& in)
|
||||
: hash (in.readInt64()),
|
||||
lastUsed (0)
|
||||
{
|
||||
const int64 len = in.readInt64();
|
||||
in.readIntoMemoryBlock (data, (ssize_t) len);
|
||||
}
|
||||
|
||||
void write (OutputStream& out)
|
||||
{
|
||||
out.writeInt64 (hash);
|
||||
out.writeInt64 ((int64) data.getSize());
|
||||
out << data;
|
||||
}
|
||||
|
||||
int64 hash;
|
||||
uint32 lastUsed;
|
||||
MemoryBlock data;
|
||||
|
||||
private:
|
||||
JUCE_LEAK_DETECTOR (ThumbnailCacheEntry)
|
||||
};
|
||||
|
||||
//==============================================================================
|
||||
AudioThumbnailCache::AudioThumbnailCache (const int maxNumThumbs)
|
||||
: thread ("thumb cache"),
|
||||
maxNumThumbsToStore (maxNumThumbs)
|
||||
{
|
||||
jassert (maxNumThumbsToStore > 0);
|
||||
thread.startThread (2);
|
||||
}
|
||||
|
||||
AudioThumbnailCache::~AudioThumbnailCache()
|
||||
{
|
||||
}
|
||||
|
||||
AudioThumbnailCache::ThumbnailCacheEntry* AudioThumbnailCache::findThumbFor (const int64 hash) const
|
||||
{
|
||||
for (int i = thumbs.size(); --i >= 0;)
|
||||
if (thumbs.getUnchecked(i)->hash == hash)
|
||||
return thumbs.getUnchecked(i);
|
||||
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
int AudioThumbnailCache::findOldestThumb() const
|
||||
{
|
||||
int oldest = 0;
|
||||
uint32 oldestTime = Time::getMillisecondCounter() + 1;
|
||||
|
||||
for (int i = thumbs.size(); --i >= 0;)
|
||||
{
|
||||
const ThumbnailCacheEntry* const te = thumbs.getUnchecked(i);
|
||||
|
||||
if (te->lastUsed < oldestTime)
|
||||
{
|
||||
oldest = i;
|
||||
oldestTime = te->lastUsed;
|
||||
}
|
||||
}
|
||||
|
||||
return oldest;
|
||||
}
|
||||
|
||||
bool AudioThumbnailCache::loadThumb (AudioThumbnailBase& thumb, const int64 hashCode)
|
||||
{
|
||||
const ScopedLock sl (lock);
|
||||
|
||||
if (ThumbnailCacheEntry* te = findThumbFor (hashCode))
|
||||
{
|
||||
te->lastUsed = Time::getMillisecondCounter();
|
||||
|
||||
MemoryInputStream in (te->data, false);
|
||||
thumb.loadFrom (in);
|
||||
return true;
|
||||
}
|
||||
|
||||
return loadNewThumb (thumb, hashCode);
|
||||
}
|
||||
|
||||
void AudioThumbnailCache::storeThumb (const AudioThumbnailBase& thumb,
|
||||
const int64 hashCode)
|
||||
{
|
||||
const ScopedLock sl (lock);
|
||||
ThumbnailCacheEntry* te = findThumbFor (hashCode);
|
||||
|
||||
if (te == nullptr)
|
||||
{
|
||||
te = new ThumbnailCacheEntry (hashCode);
|
||||
|
||||
if (thumbs.size() < maxNumThumbsToStore)
|
||||
thumbs.add (te);
|
||||
else
|
||||
thumbs.set (findOldestThumb(), te);
|
||||
}
|
||||
|
||||
{
|
||||
MemoryOutputStream out (te->data, false);
|
||||
thumb.saveTo (out);
|
||||
}
|
||||
|
||||
saveNewlyFinishedThumbnail (thumb, hashCode);
|
||||
}
|
||||
|
||||
void AudioThumbnailCache::clear()
|
||||
{
|
||||
const ScopedLock sl (lock);
|
||||
thumbs.clear();
|
||||
}
|
||||
|
||||
void AudioThumbnailCache::removeThumb (const int64 hashCode)
|
||||
{
|
||||
const ScopedLock sl (lock);
|
||||
|
||||
for (int i = thumbs.size(); --i >= 0;)
|
||||
if (thumbs.getUnchecked(i)->hash == hashCode)
|
||||
thumbs.remove (i);
|
||||
}
|
||||
|
||||
static int getThumbnailCacheFileMagicHeader() noexcept
|
||||
{
|
||||
return (int) ByteOrder::littleEndianInt ("ThmC");
|
||||
}
|
||||
|
||||
bool AudioThumbnailCache::readFromStream (InputStream& source)
|
||||
{
|
||||
if (source.readInt() != getThumbnailCacheFileMagicHeader())
|
||||
return false;
|
||||
|
||||
const ScopedLock sl (lock);
|
||||
clear();
|
||||
int numThumbnails = jmin (maxNumThumbsToStore, source.readInt());
|
||||
|
||||
while (--numThumbnails >= 0 && ! source.isExhausted())
|
||||
thumbs.add (new ThumbnailCacheEntry (source));
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
void AudioThumbnailCache::writeToStream (OutputStream& out)
|
||||
{
|
||||
const ScopedLock sl (lock);
|
||||
|
||||
out.writeInt (getThumbnailCacheFileMagicHeader());
|
||||
out.writeInt (thumbs.size());
|
||||
|
||||
for (int i = 0; i < thumbs.size(); ++i)
|
||||
thumbs.getUnchecked(i)->write (out);
|
||||
}
|
||||
|
||||
void AudioThumbnailCache::saveNewlyFinishedThumbnail (const AudioThumbnailBase&, int64)
|
||||
{
|
||||
}
|
||||
|
||||
bool AudioThumbnailCache::loadNewThumb (AudioThumbnailBase&, int64)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
} // namespace juce
|
||||
|
@ -1,118 +1,118 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE library.
|
||||
Copyright (c) 2020 - Raw Material Software Limited
|
||||
|
||||
JUCE is an open source library subject to commercial or open-source
|
||||
licensing.
|
||||
|
||||
By using JUCE, you agree to the terms of both the JUCE 6 End-User License
|
||||
Agreement and JUCE Privacy Policy (both effective as of the 16th June 2020).
|
||||
|
||||
End User License Agreement: www.juce.com/juce-6-licence
|
||||
Privacy Policy: www.juce.com/juce-privacy-policy
|
||||
|
||||
Or: You may also use this code under the terms of the GPL v3 (see
|
||||
www.gnu.org/licenses).
|
||||
|
||||
JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
|
||||
EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
|
||||
DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
//==============================================================================
|
||||
/**
|
||||
An instance of this class is used to manage multiple AudioThumbnail objects.
|
||||
|
||||
The cache runs a single background thread that is shared by all the thumbnails
|
||||
that need it, and it maintains a set of low-res previews in memory, to avoid
|
||||
having to re-scan audio files too often.
|
||||
|
||||
@see AudioThumbnail
|
||||
|
||||
@tags{Audio}
|
||||
*/
|
||||
class JUCE_API AudioThumbnailCache
|
||||
{
|
||||
public:
|
||||
//==============================================================================
|
||||
/** Creates a cache object.
|
||||
|
||||
The maxNumThumbsToStore parameter lets you specify how many previews should
|
||||
be kept in memory at once.
|
||||
*/
|
||||
explicit AudioThumbnailCache (int maxNumThumbsToStore);
|
||||
|
||||
/** Destructor. */
|
||||
virtual ~AudioThumbnailCache();
|
||||
|
||||
//==============================================================================
|
||||
/** Clears out any stored thumbnails. */
|
||||
void clear();
|
||||
|
||||
/** Reloads the specified thumb if this cache contains the appropriate stored
|
||||
data.
|
||||
|
||||
This is called automatically by the AudioThumbnail class, so you shouldn't
|
||||
normally need to call it directly.
|
||||
*/
|
||||
bool loadThumb (AudioThumbnailBase& thumb, int64 hashCode);
|
||||
|
||||
/** Stores the cachable data from the specified thumb in this cache.
|
||||
|
||||
This is called automatically by the AudioThumbnail class, so you shouldn't
|
||||
normally need to call it directly.
|
||||
*/
|
||||
void storeThumb (const AudioThumbnailBase& thumb, int64 hashCode);
|
||||
|
||||
/** Tells the cache to forget about the thumb with the given hashcode. */
|
||||
void removeThumb (int64 hashCode);
|
||||
|
||||
//==============================================================================
|
||||
/** Attempts to re-load a saved cache of thumbnails from a stream.
|
||||
The cache data must have been written by the writeToStream() method.
|
||||
This will replace all currently-loaded thumbnails with the new data.
|
||||
*/
|
||||
bool readFromStream (InputStream& source);
|
||||
|
||||
/** Writes all currently-loaded cache data to a stream.
|
||||
The resulting data can be re-loaded with readFromStream().
|
||||
*/
|
||||
void writeToStream (OutputStream& stream);
|
||||
|
||||
/** Returns the thread that client thumbnails can use. */
|
||||
TimeSliceThread& getTimeSliceThread() noexcept { return thread; }
|
||||
|
||||
protected:
|
||||
/** This can be overridden to provide a custom callback for saving thumbnails
|
||||
once they have finished being loaded.
|
||||
*/
|
||||
virtual void saveNewlyFinishedThumbnail (const AudioThumbnailBase&, int64 hashCode);
|
||||
|
||||
/** This can be overridden to provide a custom callback for loading thumbnails
|
||||
from pre-saved files to save the cache the trouble of having to create them.
|
||||
*/
|
||||
virtual bool loadNewThumb (AudioThumbnailBase&, int64 hashCode);
|
||||
|
||||
private:
|
||||
//==============================================================================
|
||||
TimeSliceThread thread;
|
||||
|
||||
class ThumbnailCacheEntry;
|
||||
OwnedArray<ThumbnailCacheEntry> thumbs;
|
||||
CriticalSection lock;
|
||||
int maxNumThumbsToStore;
|
||||
|
||||
ThumbnailCacheEntry* findThumbFor (int64 hash) const;
|
||||
int findOldestThumb() const;
|
||||
|
||||
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioThumbnailCache)
|
||||
};
|
||||
|
||||
} // namespace juce
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE library.
|
||||
Copyright (c) 2022 - Raw Material Software Limited
|
||||
|
||||
JUCE is an open source library subject to commercial or open-source
|
||||
licensing.
|
||||
|
||||
By using JUCE, you agree to the terms of both the JUCE 7 End-User License
|
||||
Agreement and JUCE Privacy Policy.
|
||||
|
||||
End User License Agreement: www.juce.com/juce-7-licence
|
||||
Privacy Policy: www.juce.com/juce-privacy-policy
|
||||
|
||||
Or: You may also use this code under the terms of the GPL v3 (see
|
||||
www.gnu.org/licenses).
|
||||
|
||||
JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
|
||||
EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
|
||||
DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
//==============================================================================
|
||||
/**
|
||||
An instance of this class is used to manage multiple AudioThumbnail objects.
|
||||
|
||||
The cache runs a single background thread that is shared by all the thumbnails
|
||||
that need it, and it maintains a set of low-res previews in memory, to avoid
|
||||
having to re-scan audio files too often.
|
||||
|
||||
@see AudioThumbnail
|
||||
|
||||
@tags{Audio}
|
||||
*/
|
||||
class JUCE_API AudioThumbnailCache
|
||||
{
|
||||
public:
|
||||
//==============================================================================
|
||||
/** Creates a cache object.
|
||||
|
||||
The maxNumThumbsToStore parameter lets you specify how many previews should
|
||||
be kept in memory at once.
|
||||
*/
|
||||
explicit AudioThumbnailCache (int maxNumThumbsToStore);
|
||||
|
||||
/** Destructor. */
|
||||
virtual ~AudioThumbnailCache();
|
||||
|
||||
//==============================================================================
|
||||
/** Clears out any stored thumbnails. */
|
||||
void clear();
|
||||
|
||||
/** Reloads the specified thumb if this cache contains the appropriate stored
|
||||
data.
|
||||
|
||||
This is called automatically by the AudioThumbnail class, so you shouldn't
|
||||
normally need to call it directly.
|
||||
*/
|
||||
bool loadThumb (AudioThumbnailBase& thumb, int64 hashCode);
|
||||
|
||||
/** Stores the cacheable data from the specified thumb in this cache.
|
||||
|
||||
This is called automatically by the AudioThumbnail class, so you shouldn't
|
||||
normally need to call it directly.
|
||||
*/
|
||||
void storeThumb (const AudioThumbnailBase& thumb, int64 hashCode);
|
||||
|
||||
/** Tells the cache to forget about the thumb with the given hashcode. */
|
||||
void removeThumb (int64 hashCode);
|
||||
|
||||
//==============================================================================
|
||||
/** Attempts to re-load a saved cache of thumbnails from a stream.
|
||||
The cache data must have been written by the writeToStream() method.
|
||||
This will replace all currently-loaded thumbnails with the new data.
|
||||
*/
|
||||
bool readFromStream (InputStream& source);
|
||||
|
||||
/** Writes all currently-loaded cache data to a stream.
|
||||
The resulting data can be re-loaded with readFromStream().
|
||||
*/
|
||||
void writeToStream (OutputStream& stream);
|
||||
|
||||
/** Returns the thread that client thumbnails can use. */
|
||||
TimeSliceThread& getTimeSliceThread() noexcept { return thread; }
|
||||
|
||||
protected:
|
||||
/** This can be overridden to provide a custom callback for saving thumbnails
|
||||
once they have finished being loaded.
|
||||
*/
|
||||
virtual void saveNewlyFinishedThumbnail (const AudioThumbnailBase&, int64 hashCode);
|
||||
|
||||
/** This can be overridden to provide a custom callback for loading thumbnails
|
||||
from pre-saved files to save the cache the trouble of having to create them.
|
||||
*/
|
||||
virtual bool loadNewThumb (AudioThumbnailBase&, int64 hashCode);
|
||||
|
||||
private:
|
||||
//==============================================================================
|
||||
TimeSliceThread thread;
|
||||
|
||||
class ThumbnailCacheEntry;
|
||||
OwnedArray<ThumbnailCacheEntry> thumbs;
|
||||
CriticalSection lock;
|
||||
int maxNumThumbsToStore;
|
||||
|
||||
ThumbnailCacheEntry* findThumbFor (int64 hash) const;
|
||||
int findOldestThumb() const;
|
||||
|
||||
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioThumbnailCache)
|
||||
};
|
||||
|
||||
} // namespace juce
|
||||
|
@ -1,222 +1,222 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE library.
|
||||
Copyright (c) 2020 - Raw Material Software Limited
|
||||
|
||||
JUCE is an open source library subject to commercial or open-source
|
||||
licensing.
|
||||
|
||||
By using JUCE, you agree to the terms of both the JUCE 6 End-User License
|
||||
Agreement and JUCE Privacy Policy (both effective as of the 16th June 2020).
|
||||
|
||||
End User License Agreement: www.juce.com/juce-6-licence
|
||||
Privacy Policy: www.juce.com/juce-privacy-policy
|
||||
|
||||
Or: You may also use this code under the terms of the GPL v3 (see
|
||||
www.gnu.org/licenses).
|
||||
|
||||
JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
|
||||
EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
|
||||
DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
struct AudioVisualiserComponent::ChannelInfo
|
||||
{
|
||||
ChannelInfo (AudioVisualiserComponent& o, int bufferSize) : owner (o)
|
||||
{
|
||||
setBufferSize (bufferSize);
|
||||
clear();
|
||||
}
|
||||
|
||||
void clear() noexcept
|
||||
{
|
||||
levels.fill ({});
|
||||
value = {};
|
||||
subSample = 0;
|
||||
}
|
||||
|
||||
void pushSamples (const float* inputSamples, int num) noexcept
|
||||
{
|
||||
for (int i = 0; i < num; ++i)
|
||||
pushSample (inputSamples[i]);
|
||||
}
|
||||
|
||||
void pushSample (float newSample) noexcept
|
||||
{
|
||||
if (--subSample <= 0)
|
||||
{
|
||||
if (++nextSample == levels.size())
|
||||
nextSample = 0;
|
||||
|
||||
levels.getReference (nextSample) = value;
|
||||
subSample = owner.getSamplesPerBlock();
|
||||
value = Range<float> (newSample, newSample);
|
||||
}
|
||||
else
|
||||
{
|
||||
value = value.getUnionWith (newSample);
|
||||
}
|
||||
}
|
||||
|
||||
void setBufferSize (int newSize)
|
||||
{
|
||||
levels.removeRange (newSize, levels.size());
|
||||
levels.insertMultiple (-1, {}, newSize - levels.size());
|
||||
|
||||
if (nextSample >= newSize)
|
||||
nextSample = 0;
|
||||
}
|
||||
|
||||
AudioVisualiserComponent& owner;
|
||||
Array<Range<float>> levels;
|
||||
Range<float> value;
|
||||
std::atomic<int> nextSample { 0 }, subSample { 0 };
|
||||
|
||||
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ChannelInfo)
|
||||
};
|
||||
|
||||
//==============================================================================
|
||||
AudioVisualiserComponent::AudioVisualiserComponent (int initialNumChannels)
|
||||
: numSamples (1024),
|
||||
inputSamplesPerBlock (256),
|
||||
backgroundColour (Colours::black),
|
||||
waveformColour (Colours::white)
|
||||
{
|
||||
setOpaque (true);
|
||||
setNumChannels (initialNumChannels);
|
||||
setRepaintRate (60);
|
||||
}
|
||||
|
||||
AudioVisualiserComponent::~AudioVisualiserComponent()
|
||||
{
|
||||
}
|
||||
|
||||
void AudioVisualiserComponent::setNumChannels (int numChannels)
|
||||
{
|
||||
channels.clear();
|
||||
|
||||
for (int i = 0; i < numChannels; ++i)
|
||||
channels.add (new ChannelInfo (*this, numSamples));
|
||||
}
|
||||
|
||||
void AudioVisualiserComponent::setBufferSize (int newNumSamples)
|
||||
{
|
||||
numSamples = newNumSamples;
|
||||
|
||||
for (auto* c : channels)
|
||||
c->setBufferSize (newNumSamples);
|
||||
}
|
||||
|
||||
void AudioVisualiserComponent::clear()
|
||||
{
|
||||
for (auto* c : channels)
|
||||
c->clear();
|
||||
}
|
||||
|
||||
void AudioVisualiserComponent::pushBuffer (const float** d, int numChannels, int num)
|
||||
{
|
||||
numChannels = jmin (numChannels, channels.size());
|
||||
|
||||
for (int i = 0; i < numChannels; ++i)
|
||||
channels.getUnchecked(i)->pushSamples (d[i], num);
|
||||
}
|
||||
|
||||
void AudioVisualiserComponent::pushBuffer (const AudioBuffer<float>& buffer)
|
||||
{
|
||||
pushBuffer (buffer.getArrayOfReadPointers(),
|
||||
buffer.getNumChannels(),
|
||||
buffer.getNumSamples());
|
||||
}
|
||||
|
||||
void AudioVisualiserComponent::pushBuffer (const AudioSourceChannelInfo& buffer)
|
||||
{
|
||||
auto numChannels = jmin (buffer.buffer->getNumChannels(), channels.size());
|
||||
|
||||
for (int i = 0; i < numChannels; ++i)
|
||||
channels.getUnchecked(i)->pushSamples (buffer.buffer->getReadPointer (i, buffer.startSample),
|
||||
buffer.numSamples);
|
||||
}
|
||||
|
||||
void AudioVisualiserComponent::pushSample (const float* d, int numChannels)
|
||||
{
|
||||
numChannels = jmin (numChannels, channels.size());
|
||||
|
||||
for (int i = 0; i < numChannels; ++i)
|
||||
channels.getUnchecked(i)->pushSample (d[i]);
|
||||
}
|
||||
|
||||
void AudioVisualiserComponent::setSamplesPerBlock (int newSamplesPerPixel) noexcept
|
||||
{
|
||||
inputSamplesPerBlock = newSamplesPerPixel;
|
||||
}
|
||||
|
||||
void AudioVisualiserComponent::setRepaintRate (int frequencyInHz)
|
||||
{
|
||||
startTimerHz (frequencyInHz);
|
||||
}
|
||||
|
||||
void AudioVisualiserComponent::timerCallback()
|
||||
{
|
||||
repaint();
|
||||
}
|
||||
|
||||
void AudioVisualiserComponent::setColours (Colour bk, Colour fg) noexcept
|
||||
{
|
||||
backgroundColour = bk;
|
||||
waveformColour = fg;
|
||||
repaint();
|
||||
}
|
||||
|
||||
void AudioVisualiserComponent::paint (Graphics& g)
|
||||
{
|
||||
g.fillAll (backgroundColour);
|
||||
|
||||
auto r = getLocalBounds().toFloat();
|
||||
auto channelHeight = r.getHeight() / (float) channels.size();
|
||||
|
||||
g.setColour (waveformColour);
|
||||
|
||||
for (auto* c : channels)
|
||||
paintChannel (g, r.removeFromTop (channelHeight),
|
||||
c->levels.begin(), c->levels.size(), c->nextSample);
|
||||
}
|
||||
|
||||
void AudioVisualiserComponent::getChannelAsPath (Path& path, const Range<float>* levels,
|
||||
int numLevels, int nextSample)
|
||||
{
|
||||
path.preallocateSpace (4 * numLevels + 8);
|
||||
|
||||
for (int i = 0; i < numLevels; ++i)
|
||||
{
|
||||
auto level = -(levels[(nextSample + i) % numLevels].getEnd());
|
||||
|
||||
if (i == 0)
|
||||
path.startNewSubPath (0.0f, level);
|
||||
else
|
||||
path.lineTo ((float) i, level);
|
||||
}
|
||||
|
||||
for (int i = numLevels; --i >= 0;)
|
||||
path.lineTo ((float) i, -(levels[(nextSample + i) % numLevels].getStart()));
|
||||
|
||||
path.closeSubPath();
|
||||
}
|
||||
|
||||
void AudioVisualiserComponent::paintChannel (Graphics& g, Rectangle<float> area,
|
||||
const Range<float>* levels, int numLevels, int nextSample)
|
||||
{
|
||||
Path p;
|
||||
getChannelAsPath (p, levels, numLevels, nextSample);
|
||||
|
||||
g.fillPath (p, AffineTransform::fromTargetPoints (0.0f, -1.0f, area.getX(), area.getY(),
|
||||
0.0f, 1.0f, area.getX(), area.getBottom(),
|
||||
(float) numLevels, -1.0f, area.getRight(), area.getY()));
|
||||
}
|
||||
|
||||
} // namespace juce
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE library.
|
||||
Copyright (c) 2022 - Raw Material Software Limited
|
||||
|
||||
JUCE is an open source library subject to commercial or open-source
|
||||
licensing.
|
||||
|
||||
By using JUCE, you agree to the terms of both the JUCE 7 End-User License
|
||||
Agreement and JUCE Privacy Policy.
|
||||
|
||||
End User License Agreement: www.juce.com/juce-7-licence
|
||||
Privacy Policy: www.juce.com/juce-privacy-policy
|
||||
|
||||
Or: You may also use this code under the terms of the GPL v3 (see
|
||||
www.gnu.org/licenses).
|
||||
|
||||
JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
|
||||
EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
|
||||
DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
struct AudioVisualiserComponent::ChannelInfo
|
||||
{
|
||||
ChannelInfo (AudioVisualiserComponent& o, int bufferSize) : owner (o)
|
||||
{
|
||||
setBufferSize (bufferSize);
|
||||
clear();
|
||||
}
|
||||
|
||||
void clear() noexcept
|
||||
{
|
||||
levels.fill ({});
|
||||
value = {};
|
||||
subSample = 0;
|
||||
}
|
||||
|
||||
void pushSamples (const float* inputSamples, int num) noexcept
|
||||
{
|
||||
for (int i = 0; i < num; ++i)
|
||||
pushSample (inputSamples[i]);
|
||||
}
|
||||
|
||||
void pushSample (float newSample) noexcept
|
||||
{
|
||||
if (--subSample <= 0)
|
||||
{
|
||||
if (++nextSample == levels.size())
|
||||
nextSample = 0;
|
||||
|
||||
levels.getReference (nextSample) = value;
|
||||
subSample = owner.getSamplesPerBlock();
|
||||
value = Range<float> (newSample, newSample);
|
||||
}
|
||||
else
|
||||
{
|
||||
value = value.getUnionWith (newSample);
|
||||
}
|
||||
}
|
||||
|
||||
void setBufferSize (int newSize)
|
||||
{
|
||||
levels.removeRange (newSize, levels.size());
|
||||
levels.insertMultiple (-1, {}, newSize - levels.size());
|
||||
|
||||
if (nextSample >= newSize)
|
||||
nextSample = 0;
|
||||
}
|
||||
|
||||
AudioVisualiserComponent& owner;
|
||||
Array<Range<float>> levels;
|
||||
Range<float> value;
|
||||
std::atomic<int> nextSample { 0 }, subSample { 0 };
|
||||
|
||||
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ChannelInfo)
|
||||
};
|
||||
|
||||
//==============================================================================
|
||||
AudioVisualiserComponent::AudioVisualiserComponent (int initialNumChannels)
|
||||
: numSamples (1024),
|
||||
inputSamplesPerBlock (256),
|
||||
backgroundColour (Colours::black),
|
||||
waveformColour (Colours::white)
|
||||
{
|
||||
setOpaque (true);
|
||||
setNumChannels (initialNumChannels);
|
||||
setRepaintRate (60);
|
||||
}
|
||||
|
||||
AudioVisualiserComponent::~AudioVisualiserComponent()
|
||||
{
|
||||
}
|
||||
|
||||
void AudioVisualiserComponent::setNumChannels (int numChannels)
|
||||
{
|
||||
channels.clear();
|
||||
|
||||
for (int i = 0; i < numChannels; ++i)
|
||||
channels.add (new ChannelInfo (*this, numSamples));
|
||||
}
|
||||
|
||||
void AudioVisualiserComponent::setBufferSize (int newNumSamples)
|
||||
{
|
||||
numSamples = newNumSamples;
|
||||
|
||||
for (auto* c : channels)
|
||||
c->setBufferSize (newNumSamples);
|
||||
}
|
||||
|
||||
void AudioVisualiserComponent::clear()
|
||||
{
|
||||
for (auto* c : channels)
|
||||
c->clear();
|
||||
}
|
||||
|
||||
void AudioVisualiserComponent::pushBuffer (const float** d, int numChannels, int num)
|
||||
{
|
||||
numChannels = jmin (numChannels, channels.size());
|
||||
|
||||
for (int i = 0; i < numChannels; ++i)
|
||||
channels.getUnchecked(i)->pushSamples (d[i], num);
|
||||
}
|
||||
|
||||
void AudioVisualiserComponent::pushBuffer (const AudioBuffer<float>& buffer)
|
||||
{
|
||||
pushBuffer (buffer.getArrayOfReadPointers(),
|
||||
buffer.getNumChannels(),
|
||||
buffer.getNumSamples());
|
||||
}
|
||||
|
||||
void AudioVisualiserComponent::pushBuffer (const AudioSourceChannelInfo& buffer)
|
||||
{
|
||||
auto numChannels = jmin (buffer.buffer->getNumChannels(), channels.size());
|
||||
|
||||
for (int i = 0; i < numChannels; ++i)
|
||||
channels.getUnchecked(i)->pushSamples (buffer.buffer->getReadPointer (i, buffer.startSample),
|
||||
buffer.numSamples);
|
||||
}
|
||||
|
||||
void AudioVisualiserComponent::pushSample (const float* d, int numChannels)
|
||||
{
|
||||
numChannels = jmin (numChannels, channels.size());
|
||||
|
||||
for (int i = 0; i < numChannels; ++i)
|
||||
channels.getUnchecked(i)->pushSample (d[i]);
|
||||
}
|
||||
|
||||
void AudioVisualiserComponent::setSamplesPerBlock (int newSamplesPerPixel) noexcept
|
||||
{
|
||||
inputSamplesPerBlock = newSamplesPerPixel;
|
||||
}
|
||||
|
||||
void AudioVisualiserComponent::setRepaintRate (int frequencyInHz)
|
||||
{
|
||||
startTimerHz (frequencyInHz);
|
||||
}
|
||||
|
||||
void AudioVisualiserComponent::timerCallback()
|
||||
{
|
||||
repaint();
|
||||
}
|
||||
|
||||
void AudioVisualiserComponent::setColours (Colour bk, Colour fg) noexcept
|
||||
{
|
||||
backgroundColour = bk;
|
||||
waveformColour = fg;
|
||||
repaint();
|
||||
}
|
||||
|
||||
void AudioVisualiserComponent::paint (Graphics& g)
|
||||
{
|
||||
g.fillAll (backgroundColour);
|
||||
|
||||
auto r = getLocalBounds().toFloat();
|
||||
auto channelHeight = r.getHeight() / (float) channels.size();
|
||||
|
||||
g.setColour (waveformColour);
|
||||
|
||||
for (auto* c : channels)
|
||||
paintChannel (g, r.removeFromTop (channelHeight),
|
||||
c->levels.begin(), c->levels.size(), c->nextSample);
|
||||
}
|
||||
|
||||
void AudioVisualiserComponent::getChannelAsPath (Path& path, const Range<float>* levels,
|
||||
int numLevels, int nextSample)
|
||||
{
|
||||
path.preallocateSpace (4 * numLevels + 8);
|
||||
|
||||
for (int i = 0; i < numLevels; ++i)
|
||||
{
|
||||
auto level = -(levels[(nextSample + i) % numLevels].getEnd());
|
||||
|
||||
if (i == 0)
|
||||
path.startNewSubPath (0.0f, level);
|
||||
else
|
||||
path.lineTo ((float) i, level);
|
||||
}
|
||||
|
||||
for (int i = numLevels; --i >= 0;)
|
||||
path.lineTo ((float) i, -(levels[(nextSample + i) % numLevels].getStart()));
|
||||
|
||||
path.closeSubPath();
|
||||
}
|
||||
|
||||
void AudioVisualiserComponent::paintChannel (Graphics& g, Rectangle<float> area,
|
||||
const Range<float>* levels, int numLevels, int nextSample)
|
||||
{
|
||||
Path p;
|
||||
getChannelAsPath (p, levels, numLevels, nextSample);
|
||||
|
||||
g.fillPath (p, AffineTransform::fromTargetPoints (0.0f, -1.0f, area.getX(), area.getY(),
|
||||
0.0f, 1.0f, area.getX(), area.getBottom(),
|
||||
(float) numLevels, -1.0f, area.getRight(), area.getY()));
|
||||
}
|
||||
|
||||
} // namespace juce
|
||||
|
@ -1,133 +1,133 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE library.
|
||||
Copyright (c) 2020 - Raw Material Software Limited
|
||||
|
||||
JUCE is an open source library subject to commercial or open-source
|
||||
licensing.
|
||||
|
||||
By using JUCE, you agree to the terms of both the JUCE 6 End-User License
|
||||
Agreement and JUCE Privacy Policy (both effective as of the 16th June 2020).
|
||||
|
||||
End User License Agreement: www.juce.com/juce-6-licence
|
||||
Privacy Policy: www.juce.com/juce-privacy-policy
|
||||
|
||||
Or: You may also use this code under the terms of the GPL v3 (see
|
||||
www.gnu.org/licenses).
|
||||
|
||||
JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
|
||||
EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
|
||||
DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
//==============================================================================
|
||||
/**
|
||||
A simple component that can be used to show a scrolling waveform of audio data.
|
||||
|
||||
This is a handy way to get a quick visualisation of some audio data. Just create
|
||||
one of these, set its size and oversampling rate, and then feed it with incoming
|
||||
data by calling one of its pushBuffer() or pushSample() methods.
|
||||
|
||||
You can override its paint method for more customised views, but it's only designed
|
||||
as a quick-and-dirty class for simple tasks, so please don't send us feature requests
|
||||
for fancy additional features that you'd like it to support! If you're building a
|
||||
real-world app that requires more powerful waveform display, you'll probably want to
|
||||
create your own component instead.
|
||||
|
||||
@tags{Audio}
|
||||
*/
|
||||
class JUCE_API AudioVisualiserComponent : public Component,
|
||||
private Timer
|
||||
{
|
||||
public:
|
||||
/** Creates a visualiser with the given number of channels. */
|
||||
AudioVisualiserComponent (int initialNumChannels);
|
||||
|
||||
/** Destructor. */
|
||||
~AudioVisualiserComponent() override;
|
||||
|
||||
/** Changes the number of channels that the visualiser stores. */
|
||||
void setNumChannels (int numChannels);
|
||||
|
||||
/** Changes the number of samples that the visualiser keeps in its history.
|
||||
Note that this value refers to the number of averaged sample blocks, and each
|
||||
block is calculated as the peak of a number of incoming audio samples. To set
|
||||
the number of incoming samples per block, use setSamplesPerBlock().
|
||||
*/
|
||||
void setBufferSize (int bufferSize);
|
||||
|
||||
/** */
|
||||
void setSamplesPerBlock (int newNumInputSamplesPerBlock) noexcept;
|
||||
|
||||
/** */
|
||||
int getSamplesPerBlock() const noexcept { return inputSamplesPerBlock; }
|
||||
|
||||
/** Clears the contents of the buffers. */
|
||||
void clear();
|
||||
|
||||
/** Pushes a buffer of channels data.
|
||||
The number of channels provided here is expected to match the number of channels
|
||||
that this AudioVisualiserComponent has been told to use.
|
||||
*/
|
||||
void pushBuffer (const AudioBuffer<float>& bufferToPush);
|
||||
|
||||
/** Pushes a buffer of channels data.
|
||||
The number of channels provided here is expected to match the number of channels
|
||||
that this AudioVisualiserComponent has been told to use.
|
||||
*/
|
||||
void pushBuffer (const AudioSourceChannelInfo& bufferToPush);
|
||||
|
||||
/** Pushes a buffer of channels data.
|
||||
The number of channels provided here is expected to match the number of channels
|
||||
that this AudioVisualiserComponent has been told to use.
|
||||
*/
|
||||
void pushBuffer (const float** channelData, int numChannels, int numSamples);
|
||||
|
||||
/** Pushes a single sample (per channel).
|
||||
The number of channels provided here is expected to match the number of channels
|
||||
that this AudioVisualiserComponent has been told to use.
|
||||
*/
|
||||
void pushSample (const float* samplesForEachChannel, int numChannels);
|
||||
|
||||
/** Sets the colours used to paint the */
|
||||
void setColours (Colour backgroundColour, Colour waveformColour) noexcept;
|
||||
|
||||
/** Sets the frequency at which the component repaints itself. */
|
||||
void setRepaintRate (int frequencyInHz);
|
||||
|
||||
/** Draws a channel of audio data in the given bounds.
|
||||
The default implementation just calls getChannelAsPath() and fits this into the given
|
||||
area. You may want to override this to draw things differently.
|
||||
*/
|
||||
virtual void paintChannel (Graphics&, Rectangle<float> bounds,
|
||||
const Range<float>* levels, int numLevels, int nextSample);
|
||||
|
||||
/** Creates a path which contains the waveform shape of a given set of range data.
|
||||
The path is normalised so that -1 and +1 are its upper and lower bounds, and it
|
||||
goes from 0 to numLevels on the X axis.
|
||||
*/
|
||||
void getChannelAsPath (Path& result, const Range<float>* levels, int numLevels, int nextSample);
|
||||
|
||||
//==============================================================================
|
||||
/** @internal */
|
||||
void paint (Graphics&) override;
|
||||
|
||||
private:
|
||||
struct ChannelInfo;
|
||||
|
||||
OwnedArray<ChannelInfo> channels;
|
||||
int numSamples, inputSamplesPerBlock;
|
||||
Colour backgroundColour, waveformColour;
|
||||
|
||||
void timerCallback() override;
|
||||
|
||||
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioVisualiserComponent)
|
||||
};
|
||||
|
||||
} // namespace juce
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE library.
|
||||
Copyright (c) 2022 - Raw Material Software Limited
|
||||
|
||||
JUCE is an open source library subject to commercial or open-source
|
||||
licensing.
|
||||
|
||||
By using JUCE, you agree to the terms of both the JUCE 7 End-User License
|
||||
Agreement and JUCE Privacy Policy.
|
||||
|
||||
End User License Agreement: www.juce.com/juce-7-licence
|
||||
Privacy Policy: www.juce.com/juce-privacy-policy
|
||||
|
||||
Or: You may also use this code under the terms of the GPL v3 (see
|
||||
www.gnu.org/licenses).
|
||||
|
||||
JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
|
||||
EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
|
||||
DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
//==============================================================================
|
||||
/**
|
||||
A simple component that can be used to show a scrolling waveform of audio data.
|
||||
|
||||
This is a handy way to get a quick visualisation of some audio data. Just create
|
||||
one of these, set its size and oversampling rate, and then feed it with incoming
|
||||
data by calling one of its pushBuffer() or pushSample() methods.
|
||||
|
||||
You can override its paint method for more customised views, but it's only designed
|
||||
as a quick-and-dirty class for simple tasks, so please don't send us feature requests
|
||||
for fancy additional features that you'd like it to support! If you're building a
|
||||
real-world app that requires more powerful waveform display, you'll probably want to
|
||||
create your own component instead.
|
||||
|
||||
@tags{Audio}
|
||||
*/
|
||||
class JUCE_API AudioVisualiserComponent : public Component,
|
||||
private Timer
|
||||
{
|
||||
public:
|
||||
/** Creates a visualiser with the given number of channels. */
|
||||
AudioVisualiserComponent (int initialNumChannels);
|
||||
|
||||
/** Destructor. */
|
||||
~AudioVisualiserComponent() override;
|
||||
|
||||
/** Changes the number of channels that the visualiser stores. */
|
||||
void setNumChannels (int numChannels);
|
||||
|
||||
/** Changes the number of samples that the visualiser keeps in its history.
|
||||
Note that this value refers to the number of averaged sample blocks, and each
|
||||
block is calculated as the peak of a number of incoming audio samples. To set
|
||||
the number of incoming samples per block, use setSamplesPerBlock().
|
||||
*/
|
||||
void setBufferSize (int bufferSize);
|
||||
|
||||
/** */
|
||||
void setSamplesPerBlock (int newNumInputSamplesPerBlock) noexcept;
|
||||
|
||||
/** */
|
||||
int getSamplesPerBlock() const noexcept { return inputSamplesPerBlock; }
|
||||
|
||||
/** Clears the contents of the buffers. */
|
||||
void clear();
|
||||
|
||||
/** Pushes a buffer of channels data.
|
||||
The number of channels provided here is expected to match the number of channels
|
||||
that this AudioVisualiserComponent has been told to use.
|
||||
*/
|
||||
void pushBuffer (const AudioBuffer<float>& bufferToPush);
|
||||
|
||||
/** Pushes a buffer of channels data.
|
||||
The number of channels provided here is expected to match the number of channels
|
||||
that this AudioVisualiserComponent has been told to use.
|
||||
*/
|
||||
void pushBuffer (const AudioSourceChannelInfo& bufferToPush);
|
||||
|
||||
/** Pushes a buffer of channels data.
|
||||
The number of channels provided here is expected to match the number of channels
|
||||
that this AudioVisualiserComponent has been told to use.
|
||||
*/
|
||||
void pushBuffer (const float** channelData, int numChannels, int numSamples);
|
||||
|
||||
/** Pushes a single sample (per channel).
|
||||
The number of channels provided here is expected to match the number of channels
|
||||
that this AudioVisualiserComponent has been told to use.
|
||||
*/
|
||||
void pushSample (const float* samplesForEachChannel, int numChannels);
|
||||
|
||||
/** Sets the colours used to paint the */
|
||||
void setColours (Colour backgroundColour, Colour waveformColour) noexcept;
|
||||
|
||||
/** Sets the frequency at which the component repaints itself. */
|
||||
void setRepaintRate (int frequencyInHz);
|
||||
|
||||
/** Draws a channel of audio data in the given bounds.
|
||||
The default implementation just calls getChannelAsPath() and fits this into the given
|
||||
area. You may want to override this to draw things differently.
|
||||
*/
|
||||
virtual void paintChannel (Graphics&, Rectangle<float> bounds,
|
||||
const Range<float>* levels, int numLevels, int nextSample);
|
||||
|
||||
/** Creates a path which contains the waveform shape of a given set of range data.
|
||||
The path is normalised so that -1 and +1 are its upper and lower bounds, and it
|
||||
goes from 0 to numLevels on the X axis.
|
||||
*/
|
||||
void getChannelAsPath (Path& result, const Range<float>* levels, int numLevels, int nextSample);
|
||||
|
||||
//==============================================================================
|
||||
/** @internal */
|
||||
void paint (Graphics&) override;
|
||||
|
||||
private:
|
||||
struct ChannelInfo;
|
||||
|
||||
OwnedArray<ChannelInfo> channels;
|
||||
int numSamples, inputSamplesPerBlock;
|
||||
Colour backgroundColour, waveformColour;
|
||||
|
||||
void timerCallback() override;
|
||||
|
||||
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioVisualiserComponent)
|
||||
};
|
||||
|
||||
} // namespace juce
|
||||
|
@ -1,83 +1,83 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE library.
|
||||
Copyright (c) 2020 - Raw Material Software Limited
|
||||
|
||||
JUCE is an open source library subject to commercial or open-source
|
||||
licensing.
|
||||
|
||||
By using JUCE, you agree to the terms of both the JUCE 6 End-User License
|
||||
Agreement and JUCE Privacy Policy (both effective as of the 16th June 2020).
|
||||
|
||||
End User License Agreement: www.juce.com/juce-6-licence
|
||||
Privacy Policy: www.juce.com/juce-privacy-policy
|
||||
|
||||
Or: You may also use this code under the terms of the GPL v3 (see
|
||||
www.gnu.org/licenses).
|
||||
|
||||
JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
|
||||
EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
|
||||
DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
//==============================================================================
|
||||
/**
|
||||
Opens a Bluetooth MIDI pairing dialogue that allows the user to view and
|
||||
connect to Bluetooth MIDI devices that are currently found nearby.
|
||||
|
||||
The dialogue will ignore non-MIDI Bluetooth devices.
|
||||
|
||||
Only after a Bluetooth MIDI device has been paired will its MIDI ports
|
||||
be available through JUCE's MidiInput and MidiOutput classes.
|
||||
|
||||
This dialogue is currently only available on macOS targetting versions 10.11+,
|
||||
iOS and Android. When targeting older versions of macOS you should instead
|
||||
pair Bluetooth MIDI devices using the "Audio MIDI Setup" app (located in
|
||||
/Applications/Utilities). On Windows, you should use the system settings. On
|
||||
Linux, Bluetooth MIDI devices are currently not supported.
|
||||
|
||||
@tags{Audio}
|
||||
*/
|
||||
class JUCE_API BluetoothMidiDevicePairingDialogue
|
||||
{
|
||||
public:
|
||||
|
||||
/** Opens the Bluetooth MIDI pairing dialogue, if it is available.
|
||||
|
||||
@param exitCallback A callback which will be called when the modal
|
||||
bluetooth dialog is closed.
|
||||
@param btWindowBounds The bounds of the bluetooth window that will
|
||||
be opened. The dialog itself is opened by the OS so cannot
|
||||
be customised by JUCE.
|
||||
@return true if the dialogue was opened, false on error.
|
||||
|
||||
@see ModalComponentManager::Callback
|
||||
*/
|
||||
static bool open (ModalComponentManager::Callback* exitCallback = nullptr,
|
||||
Rectangle<int>* btWindowBounds = nullptr);
|
||||
|
||||
/** Checks if a Bluetooth MIDI pairing dialogue is available on this
|
||||
platform.
|
||||
|
||||
On iOS, this will be true for iOS versions 8.0 and higher.
|
||||
|
||||
On Android, this will be true only for Android SDK versions 23 and
|
||||
higher, and additionally only if the device itself supports MIDI
|
||||
over Bluetooth.
|
||||
|
||||
On desktop platforms, this will typically be false as the bluetooth
|
||||
pairing is not done inside the app but by other means.
|
||||
|
||||
@return true if the Bluetooth MIDI pairing dialogue is available,
|
||||
false otherwise.
|
||||
*/
|
||||
static bool isAvailable();
|
||||
};
|
||||
|
||||
} // namespace juce
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE library.
|
||||
Copyright (c) 2022 - Raw Material Software Limited
|
||||
|
||||
JUCE is an open source library subject to commercial or open-source
|
||||
licensing.
|
||||
|
||||
By using JUCE, you agree to the terms of both the JUCE 7 End-User License
|
||||
Agreement and JUCE Privacy Policy.
|
||||
|
||||
End User License Agreement: www.juce.com/juce-7-licence
|
||||
Privacy Policy: www.juce.com/juce-privacy-policy
|
||||
|
||||
Or: You may also use this code under the terms of the GPL v3 (see
|
||||
www.gnu.org/licenses).
|
||||
|
||||
JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
|
||||
EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
|
||||
DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
//==============================================================================
|
||||
/**
|
||||
Opens a Bluetooth MIDI pairing dialogue that allows the user to view and
|
||||
connect to Bluetooth MIDI devices that are currently found nearby.
|
||||
|
||||
The dialogue will ignore non-MIDI Bluetooth devices.
|
||||
|
||||
Only after a Bluetooth MIDI device has been paired will its MIDI ports
|
||||
be available through JUCE's MidiInput and MidiOutput classes.
|
||||
|
||||
This dialogue is currently only available on macOS targeting versions 10.11+,
|
||||
iOS and Android. When targeting older versions of macOS you should instead
|
||||
pair Bluetooth MIDI devices using the "Audio MIDI Setup" app (located in
|
||||
/Applications/Utilities). On Windows, you should use the system settings. On
|
||||
Linux, Bluetooth MIDI devices are currently not supported.
|
||||
|
||||
@tags{Audio}
|
||||
*/
|
||||
class JUCE_API BluetoothMidiDevicePairingDialogue
|
||||
{
|
||||
public:
|
||||
|
||||
/** Opens the Bluetooth MIDI pairing dialogue, if it is available.
|
||||
|
||||
@param exitCallback A callback which will be called when the modal
|
||||
bluetooth dialog is closed.
|
||||
@param btWindowBounds The bounds of the bluetooth window that will
|
||||
be opened. The dialog itself is opened by the OS so cannot
|
||||
be customised by JUCE.
|
||||
@return true if the dialogue was opened, false on error.
|
||||
|
||||
@see ModalComponentManager::Callback
|
||||
*/
|
||||
static bool open (ModalComponentManager::Callback* exitCallback = nullptr,
|
||||
Rectangle<int>* btWindowBounds = nullptr);
|
||||
|
||||
/** Checks if a Bluetooth MIDI pairing dialogue is available on this
|
||||
platform.
|
||||
|
||||
On iOS, this will be true for iOS versions 8.0 and higher.
|
||||
|
||||
On Android, this will be true only for Android SDK versions 23 and
|
||||
higher, and additionally only if the device itself supports MIDI
|
||||
over Bluetooth.
|
||||
|
||||
On desktop platforms, this will typically be false as the bluetooth
|
||||
pairing is not done inside the app but by other means.
|
||||
|
||||
@return true if the Bluetooth MIDI pairing dialogue is available,
|
||||
false otherwise.
|
||||
*/
|
||||
static bool isAvailable();
|
||||
};
|
||||
|
||||
} // namespace juce
|
||||
|
462
deps/juce/modules/juce_audio_utils/gui/juce_KeyboardComponentBase.cpp
vendored
Normal file
462
deps/juce/modules/juce_audio_utils/gui/juce_KeyboardComponentBase.cpp
vendored
Normal file
@ -0,0 +1,462 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE library.
|
||||
Copyright (c) 2022 - Raw Material Software Limited
|
||||
|
||||
JUCE is an open source library subject to commercial or open-source
|
||||
licensing.
|
||||
|
||||
By using JUCE, you agree to the terms of both the JUCE 7 End-User License
|
||||
Agreement and JUCE Privacy Policy.
|
||||
|
||||
End User License Agreement: www.juce.com/juce-7-licence
|
||||
Privacy Policy: www.juce.com/juce-privacy-policy
|
||||
|
||||
Or: You may also use this code under the terms of the GPL v3 (see
|
||||
www.gnu.org/licenses).
|
||||
|
||||
JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
|
||||
EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
|
||||
DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
constexpr uint8 whiteNotes[] = { 0, 2, 4, 5, 7, 9, 11 };
|
||||
constexpr uint8 blackNotes[] = { 1, 3, 6, 8, 10 };
|
||||
|
||||
//==============================================================================
|
||||
struct KeyboardComponentBase::UpDownButton : public Button
|
||||
{
|
||||
UpDownButton (KeyboardComponentBase& c, int d)
|
||||
: Button ({}), owner (c), delta (d)
|
||||
{
|
||||
}
|
||||
|
||||
void clicked() override
|
||||
{
|
||||
auto note = owner.getLowestVisibleKey();
|
||||
|
||||
note = delta < 0 ? (note - 1) / 12 : note / 12 + 1;
|
||||
|
||||
owner.setLowestVisibleKey (note * 12);
|
||||
}
|
||||
|
||||
using Button::clicked;
|
||||
|
||||
void paintButton (Graphics& g, bool shouldDrawButtonAsHighlighted, bool shouldDrawButtonAsDown) override
|
||||
{
|
||||
owner.drawUpDownButton (g, getWidth(), getHeight(),
|
||||
shouldDrawButtonAsHighlighted, shouldDrawButtonAsDown,
|
||||
delta > 0);
|
||||
}
|
||||
|
||||
private:
|
||||
KeyboardComponentBase& owner;
|
||||
int delta;
|
||||
|
||||
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (UpDownButton)
|
||||
};
|
||||
|
||||
//==============================================================================
|
||||
KeyboardComponentBase::KeyboardComponentBase (Orientation o) : orientation (o)
|
||||
{
|
||||
scrollDown = std::make_unique<UpDownButton> (*this, -1);
|
||||
scrollUp = std::make_unique<UpDownButton> (*this, 1);
|
||||
|
||||
addChildComponent (*scrollDown);
|
||||
addChildComponent (*scrollUp);
|
||||
|
||||
colourChanged();
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
void KeyboardComponentBase::setKeyWidth (float widthInPixels)
|
||||
{
|
||||
jassert (widthInPixels > 0);
|
||||
|
||||
if (keyWidth != widthInPixels) // Prevent infinite recursion if the width is being computed in a 'resized()' callback
|
||||
{
|
||||
keyWidth = widthInPixels;
|
||||
resized();
|
||||
}
|
||||
}
|
||||
|
||||
void KeyboardComponentBase::setScrollButtonWidth (int widthInPixels)
|
||||
{
|
||||
jassert (widthInPixels > 0);
|
||||
|
||||
if (scrollButtonWidth != widthInPixels)
|
||||
{
|
||||
scrollButtonWidth = widthInPixels;
|
||||
resized();
|
||||
}
|
||||
}
|
||||
|
||||
void KeyboardComponentBase::setOrientation (Orientation newOrientation)
|
||||
{
|
||||
if (orientation != newOrientation)
|
||||
{
|
||||
orientation = newOrientation;
|
||||
resized();
|
||||
}
|
||||
}
|
||||
|
||||
void KeyboardComponentBase::setAvailableRange (int lowestNote, int highestNote)
|
||||
{
|
||||
jassert (lowestNote >= 0 && lowestNote <= 127);
|
||||
jassert (highestNote >= 0 && highestNote <= 127);
|
||||
jassert (lowestNote <= highestNote);
|
||||
|
||||
if (rangeStart != lowestNote || rangeEnd != highestNote)
|
||||
{
|
||||
rangeStart = jlimit (0, 127, lowestNote);
|
||||
rangeEnd = jlimit (0, 127, highestNote);
|
||||
firstKey = jlimit ((float) rangeStart, (float) rangeEnd, firstKey);
|
||||
resized();
|
||||
}
|
||||
}
|
||||
|
||||
void KeyboardComponentBase::setLowestVisibleKey (int noteNumber)
|
||||
{
|
||||
setLowestVisibleKeyFloat ((float) noteNumber);
|
||||
}
|
||||
|
||||
void KeyboardComponentBase::setLowestVisibleKeyFloat (float noteNumber)
|
||||
{
|
||||
noteNumber = jlimit ((float) rangeStart, (float) rangeEnd, noteNumber);
|
||||
|
||||
if (noteNumber != firstKey)
|
||||
{
|
||||
bool hasMoved = (((int) firstKey) != (int) noteNumber);
|
||||
firstKey = noteNumber;
|
||||
|
||||
if (hasMoved)
|
||||
sendChangeMessage();
|
||||
|
||||
resized();
|
||||
}
|
||||
}
|
||||
|
||||
float KeyboardComponentBase::getWhiteNoteLength() const noexcept
|
||||
{
|
||||
return (orientation == horizontalKeyboard) ? (float) getHeight() : (float) getWidth();
|
||||
}
|
||||
|
||||
void KeyboardComponentBase::setBlackNoteLengthProportion (float ratio) noexcept
|
||||
{
|
||||
jassert (ratio >= 0.0f && ratio <= 1.0f);
|
||||
|
||||
if (blackNoteLengthRatio != ratio)
|
||||
{
|
||||
blackNoteLengthRatio = ratio;
|
||||
resized();
|
||||
}
|
||||
}
|
||||
|
||||
float KeyboardComponentBase::getBlackNoteLength() const noexcept
|
||||
{
|
||||
auto whiteNoteLength = orientation == horizontalKeyboard ? getHeight() : getWidth();
|
||||
return (float) whiteNoteLength * blackNoteLengthRatio;
|
||||
}
|
||||
|
||||
void KeyboardComponentBase::setBlackNoteWidthProportion (float ratio) noexcept
|
||||
{
|
||||
jassert (ratio >= 0.0f && ratio <= 1.0f);
|
||||
|
||||
if (blackNoteWidthRatio != ratio)
|
||||
{
|
||||
blackNoteWidthRatio = ratio;
|
||||
resized();
|
||||
}
|
||||
}
|
||||
|
||||
void KeyboardComponentBase::setScrollButtonsVisible (bool newCanScroll)
|
||||
{
|
||||
if (canScroll != newCanScroll)
|
||||
{
|
||||
canScroll = newCanScroll;
|
||||
resized();
|
||||
}
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
Range<float> KeyboardComponentBase::getKeyPos (int midiNoteNumber) const
|
||||
{
|
||||
return getKeyPosition (midiNoteNumber, keyWidth)
|
||||
- xOffset
|
||||
- getKeyPosition (rangeStart, keyWidth).getStart();
|
||||
}
|
||||
|
||||
float KeyboardComponentBase::getKeyStartPosition (int midiNoteNumber) const
|
||||
{
|
||||
return getKeyPos (midiNoteNumber).getStart();
|
||||
}
|
||||
|
||||
float KeyboardComponentBase::getTotalKeyboardWidth() const noexcept
|
||||
{
|
||||
return getKeyPos (rangeEnd).getEnd();
|
||||
}
|
||||
|
||||
KeyboardComponentBase::NoteAndVelocity KeyboardComponentBase::getNoteAndVelocityAtPosition (Point<float> pos, bool children)
|
||||
{
|
||||
if (! reallyContains (pos, children))
|
||||
return { -1, 0.0f };
|
||||
|
||||
auto p = pos;
|
||||
|
||||
if (orientation != horizontalKeyboard)
|
||||
{
|
||||
p = { p.y, p.x };
|
||||
|
||||
if (orientation == verticalKeyboardFacingLeft)
|
||||
p = { p.x, (float) getWidth() - p.y };
|
||||
else
|
||||
p = { (float) getHeight() - p.x, p.y };
|
||||
}
|
||||
|
||||
return remappedXYToNote (p + Point<float> (xOffset, 0));
|
||||
}
|
||||
|
||||
KeyboardComponentBase::NoteAndVelocity KeyboardComponentBase::remappedXYToNote (Point<float> pos) const
|
||||
{
|
||||
auto blackNoteLength = getBlackNoteLength();
|
||||
|
||||
if (pos.getY() < blackNoteLength)
|
||||
{
|
||||
for (int octaveStart = 12 * (rangeStart / 12); octaveStart <= rangeEnd; octaveStart += 12)
|
||||
{
|
||||
for (int i = 0; i < 5; ++i)
|
||||
{
|
||||
auto note = octaveStart + blackNotes[i];
|
||||
|
||||
if (rangeStart <= note && note <= rangeEnd)
|
||||
{
|
||||
if (getKeyPos (note).contains (pos.x - xOffset))
|
||||
{
|
||||
return { note, jmax (0.0f, pos.y / blackNoteLength) };
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (int octaveStart = 12 * (rangeStart / 12); octaveStart <= rangeEnd; octaveStart += 12)
|
||||
{
|
||||
for (int i = 0; i < 7; ++i)
|
||||
{
|
||||
auto note = octaveStart + whiteNotes[i];
|
||||
|
||||
if (note >= rangeStart && note <= rangeEnd)
|
||||
{
|
||||
if (getKeyPos (note).contains (pos.x - xOffset))
|
||||
{
|
||||
auto whiteNoteLength = (orientation == horizontalKeyboard) ? getHeight() : getWidth();
|
||||
return { note, jmax (0.0f, pos.y / (float) whiteNoteLength) };
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return { -1, 0 };
|
||||
}
|
||||
|
||||
Rectangle<float> KeyboardComponentBase::getRectangleForKey (int note) const
|
||||
{
|
||||
jassert (note >= rangeStart && note <= rangeEnd);
|
||||
|
||||
auto pos = getKeyPos (note);
|
||||
auto x = pos.getStart();
|
||||
auto w = pos.getLength();
|
||||
|
||||
if (MidiMessage::isMidiNoteBlack (note))
|
||||
{
|
||||
auto blackNoteLength = getBlackNoteLength();
|
||||
|
||||
switch (orientation)
|
||||
{
|
||||
case horizontalKeyboard: return { x, 0, w, blackNoteLength };
|
||||
case verticalKeyboardFacingLeft: return { (float) getWidth() - blackNoteLength, x, blackNoteLength, w };
|
||||
case verticalKeyboardFacingRight: return { 0, (float) getHeight() - x - w, blackNoteLength, w };
|
||||
default: jassertfalse; break;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
switch (orientation)
|
||||
{
|
||||
case horizontalKeyboard: return { x, 0, w, (float) getHeight() };
|
||||
case verticalKeyboardFacingLeft: return { 0, x, (float) getWidth(), w };
|
||||
case verticalKeyboardFacingRight: return { 0, (float) getHeight() - x - w, (float) getWidth(), w };
|
||||
default: jassertfalse; break;
|
||||
}
|
||||
}
|
||||
|
||||
return {};
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
void KeyboardComponentBase::setOctaveForMiddleC (int octaveNum)
|
||||
{
|
||||
octaveNumForMiddleC = octaveNum;
|
||||
repaint();
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
void KeyboardComponentBase::drawUpDownButton (Graphics& g, int w, int h, bool mouseOver, bool buttonDown, bool movesOctavesUp)
|
||||
{
|
||||
g.fillAll (findColour (upDownButtonBackgroundColourId));
|
||||
|
||||
float angle = 0;
|
||||
|
||||
switch (getOrientation())
|
||||
{
|
||||
case horizontalKeyboard: angle = movesOctavesUp ? 0.0f : 0.5f; break;
|
||||
case verticalKeyboardFacingLeft: angle = movesOctavesUp ? 0.25f : 0.75f; break;
|
||||
case verticalKeyboardFacingRight: angle = movesOctavesUp ? 0.75f : 0.25f; break;
|
||||
default: jassertfalse; break;
|
||||
}
|
||||
|
||||
Path path;
|
||||
path.addTriangle (0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.5f);
|
||||
path.applyTransform (AffineTransform::rotation (MathConstants<float>::twoPi * angle, 0.5f, 0.5f));
|
||||
|
||||
g.setColour (findColour (upDownButtonArrowColourId)
|
||||
.withAlpha (buttonDown ? 1.0f : (mouseOver ? 0.6f : 0.4f)));
|
||||
|
||||
g.fillPath (path, path.getTransformToScaleToFit (1.0f, 1.0f, (float) w - 2.0f, (float) h - 2.0f, true));
|
||||
}
|
||||
|
||||
Range<float> KeyboardComponentBase::getKeyPosition (int midiNoteNumber, float targetKeyWidth) const
|
||||
{
|
||||
auto ratio = getBlackNoteWidthProportion();
|
||||
|
||||
static const float notePos[] = { 0.0f, 1 - ratio * 0.6f,
|
||||
1.0f, 2 - ratio * 0.4f,
|
||||
2.0f,
|
||||
3.0f, 4 - ratio * 0.7f,
|
||||
4.0f, 5 - ratio * 0.5f,
|
||||
5.0f, 6 - ratio * 0.3f,
|
||||
6.0f };
|
||||
|
||||
auto octave = midiNoteNumber / 12;
|
||||
auto note = midiNoteNumber % 12;
|
||||
|
||||
auto start = (float) octave * 7.0f * targetKeyWidth + notePos[note] * targetKeyWidth;
|
||||
auto width = MidiMessage::isMidiNoteBlack (note) ? blackNoteWidthRatio * targetKeyWidth : targetKeyWidth;
|
||||
|
||||
return { start, start + width };
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
void KeyboardComponentBase::paint (Graphics& g)
|
||||
{
|
||||
drawKeyboardBackground (g, getLocalBounds().toFloat());
|
||||
|
||||
for (int octaveBase = 0; octaveBase < 128; octaveBase += 12)
|
||||
{
|
||||
for (auto noteNum : whiteNotes)
|
||||
{
|
||||
const auto key = octaveBase + noteNum;
|
||||
|
||||
if (rangeStart <= key && key <= rangeEnd)
|
||||
drawWhiteKey (key, g, getRectangleForKey (key));
|
||||
}
|
||||
|
||||
for (auto noteNum : blackNotes)
|
||||
{
|
||||
const auto key = octaveBase + noteNum;
|
||||
|
||||
if (rangeStart <= key && key <= rangeEnd)
|
||||
drawBlackKey (key, g, getRectangleForKey (key));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void KeyboardComponentBase::resized()
|
||||
{
|
||||
auto w = getWidth();
|
||||
auto h = getHeight();
|
||||
|
||||
if (w > 0 && h > 0)
|
||||
{
|
||||
if (orientation != horizontalKeyboard)
|
||||
std::swap (w, h);
|
||||
|
||||
auto kx2 = getKeyPos (rangeEnd).getEnd();
|
||||
|
||||
if ((int) firstKey != rangeStart)
|
||||
{
|
||||
auto kx1 = getKeyPos (rangeStart).getStart();
|
||||
|
||||
if (kx2 - kx1 <= (float) w)
|
||||
{
|
||||
firstKey = (float) rangeStart;
|
||||
sendChangeMessage();
|
||||
repaint();
|
||||
}
|
||||
}
|
||||
|
||||
scrollDown->setVisible (canScroll && firstKey > (float) rangeStart);
|
||||
|
||||
xOffset = 0;
|
||||
|
||||
if (canScroll)
|
||||
{
|
||||
auto scrollButtonW = jmin (scrollButtonWidth, w / 2);
|
||||
auto r = getLocalBounds();
|
||||
|
||||
if (orientation == horizontalKeyboard)
|
||||
{
|
||||
scrollDown->setBounds (r.removeFromLeft (scrollButtonW));
|
||||
scrollUp ->setBounds (r.removeFromRight (scrollButtonW));
|
||||
}
|
||||
else if (orientation == verticalKeyboardFacingLeft)
|
||||
{
|
||||
scrollDown->setBounds (r.removeFromTop (scrollButtonW));
|
||||
scrollUp ->setBounds (r.removeFromBottom (scrollButtonW));
|
||||
}
|
||||
else
|
||||
{
|
||||
scrollDown->setBounds (r.removeFromBottom (scrollButtonW));
|
||||
scrollUp ->setBounds (r.removeFromTop (scrollButtonW));
|
||||
}
|
||||
|
||||
auto endOfLastKey = getKeyPos (rangeEnd).getEnd();
|
||||
|
||||
auto spaceAvailable = w;
|
||||
auto lastStartKey = remappedXYToNote ({ endOfLastKey - (float) spaceAvailable, 0 }).note + 1;
|
||||
|
||||
if (lastStartKey >= 0 && ((int) firstKey) > lastStartKey)
|
||||
{
|
||||
firstKey = (float) jlimit (rangeStart, rangeEnd, lastStartKey);
|
||||
sendChangeMessage();
|
||||
}
|
||||
|
||||
xOffset = getKeyPos ((int) firstKey).getStart();
|
||||
}
|
||||
else
|
||||
{
|
||||
firstKey = (float) rangeStart;
|
||||
}
|
||||
|
||||
scrollUp->setVisible (canScroll && getKeyPos (rangeEnd).getStart() > (float) w);
|
||||
repaint();
|
||||
}
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
void KeyboardComponentBase::mouseWheelMove (const MouseEvent&, const MouseWheelDetails& wheel)
|
||||
{
|
||||
auto amount = (orientation == horizontalKeyboard && wheel.deltaX != 0)
|
||||
? wheel.deltaX : (orientation == verticalKeyboardFacingLeft ? wheel.deltaY
|
||||
: -wheel.deltaY);
|
||||
|
||||
setLowestVisibleKeyFloat (firstKey - amount * keyWidth);
|
||||
}
|
||||
|
||||
} // namespace juce
|
295
deps/juce/modules/juce_audio_utils/gui/juce_KeyboardComponentBase.h
vendored
Normal file
295
deps/juce/modules/juce_audio_utils/gui/juce_KeyboardComponentBase.h
vendored
Normal file
@ -0,0 +1,295 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE library.
|
||||
Copyright (c) 2022 - Raw Material Software Limited
|
||||
|
||||
JUCE is an open source library subject to commercial or open-source
|
||||
licensing.
|
||||
|
||||
By using JUCE, you agree to the terms of both the JUCE 7 End-User License
|
||||
Agreement and JUCE Privacy Policy.
|
||||
|
||||
End User License Agreement: www.juce.com/juce-7-licence
|
||||
Privacy Policy: www.juce.com/juce-privacy-policy
|
||||
|
||||
Or: You may also use this code under the terms of the GPL v3 (see
|
||||
www.gnu.org/licenses).
|
||||
|
||||
JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
|
||||
EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
|
||||
DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
//==============================================================================
|
||||
/**
|
||||
A base class for drawing a custom MIDI keyboard component.
|
||||
|
||||
Implement the drawKeyboardBackground(), drawWhiteKey(), and drawBlackKey() methods
|
||||
to draw your content and this class will handle the underlying keyboard logic.
|
||||
|
||||
The component is a ChangeBroadcaster, so if you want to be informed when the
|
||||
keyboard is scrolled, you can register a ChangeListener for callbacks.
|
||||
|
||||
@tags{Audio}
|
||||
*/
|
||||
class JUCE_API KeyboardComponentBase : public Component,
|
||||
public ChangeBroadcaster
|
||||
{
|
||||
public:
|
||||
//==============================================================================
|
||||
/** The direction of the keyboard.
|
||||
|
||||
@see setOrientation
|
||||
*/
|
||||
enum Orientation
|
||||
{
|
||||
horizontalKeyboard,
|
||||
verticalKeyboardFacingLeft,
|
||||
verticalKeyboardFacingRight,
|
||||
};
|
||||
|
||||
//==============================================================================
|
||||
/** Constructor.
|
||||
|
||||
@param orientation whether the keyboard is horizontal or vertical
|
||||
*/
|
||||
explicit KeyboardComponentBase (Orientation orientation);
|
||||
|
||||
/** Destructor. */
|
||||
~KeyboardComponentBase() override = default;
|
||||
|
||||
//==============================================================================
|
||||
/** Changes the width used to draw the white keys. */
|
||||
void setKeyWidth (float widthInPixels);
|
||||
|
||||
/** Returns the width that was set by setKeyWidth(). */
|
||||
float getKeyWidth() const noexcept { return keyWidth; }
|
||||
|
||||
/** Changes the width used to draw the buttons that scroll the keyboard up/down in octaves. */
|
||||
void setScrollButtonWidth (int widthInPixels);
|
||||
|
||||
/** Returns the width that was set by setScrollButtonWidth(). */
|
||||
int getScrollButtonWidth() const noexcept { return scrollButtonWidth; }
|
||||
|
||||
/** Changes the keyboard's current direction. */
|
||||
void setOrientation (Orientation newOrientation);
|
||||
|
||||
/** Returns the keyboard's current direction. */
|
||||
Orientation getOrientation() const noexcept { return orientation; }
|
||||
|
||||
/** Returns true if the keyboard's orientation is horizontal. */
|
||||
bool isHorizontal() const noexcept { return orientation == horizontalKeyboard; }
|
||||
|
||||
/** Sets the range of midi notes that the keyboard will be limited to.
|
||||
|
||||
By default the range is 0 to 127 (inclusive), but you can limit this if you
|
||||
only want a restricted set of the keys to be shown.
|
||||
|
||||
Note that the values here are inclusive and must be between 0 and 127.
|
||||
*/
|
||||
void setAvailableRange (int lowestNote, int highestNote);
|
||||
|
||||
/** Returns the first note in the available range.
|
||||
|
||||
@see setAvailableRange
|
||||
*/
|
||||
int getRangeStart() const noexcept { return rangeStart; }
|
||||
|
||||
/** Returns the last note in the available range.
|
||||
|
||||
@see setAvailableRange
|
||||
*/
|
||||
int getRangeEnd() const noexcept { return rangeEnd; }
|
||||
|
||||
/** If the keyboard extends beyond the size of the component, this will scroll
|
||||
it to show the given key at the start.
|
||||
|
||||
Whenever the keyboard's position is changed, this will use the ChangeBroadcaster
|
||||
base class to send a callback to any ChangeListeners that have been registered.
|
||||
*/
|
||||
void setLowestVisibleKey (int noteNumber);
|
||||
|
||||
/** Returns the number of the first key shown in the component.
|
||||
|
||||
@see setLowestVisibleKey
|
||||
*/
|
||||
int getLowestVisibleKey() const noexcept { return (int) firstKey; }
|
||||
|
||||
/** Returns the absolute length of the white notes.
|
||||
|
||||
This will be their vertical or horizontal length, depending on the keyboard's orientation.
|
||||
*/
|
||||
float getWhiteNoteLength() const noexcept;
|
||||
|
||||
/** Sets the length of the black notes as a proportion of the white note length. */
|
||||
void setBlackNoteLengthProportion (float ratio) noexcept;
|
||||
|
||||
/** Returns the length of the black notes as a proportion of the white note length. */
|
||||
float getBlackNoteLengthProportion() const noexcept { return blackNoteLengthRatio; }
|
||||
|
||||
/** Returns the absolute length of the black notes.
|
||||
|
||||
This will be their vertical or horizontal length, depending on the keyboard's orientation.
|
||||
*/
|
||||
float getBlackNoteLength() const noexcept;
|
||||
|
||||
/** Sets the width of the black notes as a proportion of the white note width. */
|
||||
void setBlackNoteWidthProportion (float ratio) noexcept;
|
||||
|
||||
/** Returns the width of the black notes as a proportion of the white note width. */
|
||||
float getBlackNoteWidthProportion() const noexcept { return blackNoteWidthRatio; }
|
||||
|
||||
/** Returns the absolute width of the black notes.
|
||||
|
||||
This will be their vertical or horizontal width, depending on the keyboard's orientation.
|
||||
*/
|
||||
float getBlackNoteWidth() const noexcept { return keyWidth * blackNoteWidthRatio; }
|
||||
|
||||
/** If set to true, then scroll buttons will appear at either end of the keyboard
|
||||
if there are too many notes to fit them all in the component at once.
|
||||
*/
|
||||
void setScrollButtonsVisible (bool canScroll);
|
||||
|
||||
//==============================================================================
|
||||
/** Colour IDs to use to change the colour of the octave scroll buttons.
|
||||
|
||||
These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
|
||||
methods.
|
||||
|
||||
@see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
|
||||
*/
|
||||
enum ColourIds
|
||||
{
|
||||
upDownButtonBackgroundColourId = 0x1004000,
|
||||
upDownButtonArrowColourId = 0x1004001
|
||||
};
|
||||
|
||||
/** Returns the position within the component of the left-hand edge of a key.
|
||||
|
||||
Depending on the keyboard's orientation, this may be a horizontal or vertical
|
||||
distance, in either direction.
|
||||
*/
|
||||
float getKeyStartPosition (int midiNoteNumber) const;
|
||||
|
||||
/** Returns the total width needed to fit all the keys in the available range. */
|
||||
float getTotalKeyboardWidth() const noexcept;
|
||||
|
||||
/** This structure is returned by the getNoteAndVelocityAtPosition() method.
|
||||
*/
|
||||
struct JUCE_API NoteAndVelocity
|
||||
{
|
||||
int note;
|
||||
float velocity;
|
||||
};
|
||||
|
||||
/** Returns the note number and velocity for a given position within the component.
|
||||
|
||||
If includeChildComponents is true then this will return a key obscured by any child
|
||||
components.
|
||||
*/
|
||||
NoteAndVelocity getNoteAndVelocityAtPosition (Point<float> position, bool includeChildComponents = false);
|
||||
|
||||
#ifndef DOXYGEN
|
||||
/** Returns the key at a given coordinate, or -1 if the position does not intersect a key. */
|
||||
[[deprecated ("This method has been deprecated in favour of getNoteAndVelocityAtPosition.")]]
|
||||
int getNoteAtPosition (Point<float> p) { return getNoteAndVelocityAtPosition (p).note; }
|
||||
#endif
|
||||
|
||||
/** Returns the rectangle for a given key. */
|
||||
Rectangle<float> getRectangleForKey (int midiNoteNumber) const;
|
||||
|
||||
//==============================================================================
|
||||
/** This sets the octave number which is shown as the octave number for middle C.
|
||||
|
||||
This affects only the default implementation of getWhiteNoteText(), which
|
||||
passes this octave number to MidiMessage::getMidiNoteName() in order to
|
||||
get the note text. See MidiMessage::getMidiNoteName() for more info about
|
||||
the parameter.
|
||||
|
||||
By default this value is set to 3.
|
||||
|
||||
@see getOctaveForMiddleC
|
||||
*/
|
||||
void setOctaveForMiddleC (int octaveNumForMiddleC);
|
||||
|
||||
/** This returns the value set by setOctaveForMiddleC().
|
||||
|
||||
@see setOctaveForMiddleC
|
||||
*/
|
||||
int getOctaveForMiddleC() const noexcept { return octaveNumForMiddleC; }
|
||||
|
||||
//==============================================================================
|
||||
/** Use this method to draw the background of the keyboard that will be drawn under
|
||||
the white and black notes. This can also be used to draw any shadow or outline effects.
|
||||
*/
|
||||
virtual void drawKeyboardBackground (Graphics& g, Rectangle<float> area) = 0;
|
||||
|
||||
/** Use this method to draw a white key of the keyboard in a given rectangle.
|
||||
|
||||
When doing this, be sure to note the keyboard's orientation.
|
||||
*/
|
||||
virtual void drawWhiteKey (int midiNoteNumber, Graphics& g, Rectangle<float> area) = 0;
|
||||
|
||||
/** Use this method to draw a black key of the keyboard in a given rectangle.
|
||||
|
||||
When doing this, be sure to note the keyboard's orientation.
|
||||
*/
|
||||
virtual void drawBlackKey (int midiNoteNumber, Graphics& g, Rectangle<float> area) = 0;
|
||||
|
||||
/** This can be overridden to draw the up and down buttons that scroll the keyboard
|
||||
up/down in octaves.
|
||||
*/
|
||||
virtual void drawUpDownButton (Graphics& g, int w, int h, bool isMouseOver, bool isButtonPressed, bool movesOctavesUp);
|
||||
|
||||
/** Calculates the position of a given midi-note.
|
||||
|
||||
This can be overridden to create layouts with custom key-widths.
|
||||
|
||||
@param midiNoteNumber the note to find
|
||||
@param keyWidth the desired width in pixels of one key - see setKeyWidth()
|
||||
@returns the start and length of the key along the axis of the keyboard
|
||||
*/
|
||||
virtual Range<float> getKeyPosition (int midiNoteNumber, float keyWidth) const;
|
||||
|
||||
//==============================================================================
|
||||
/** @internal */
|
||||
void paint (Graphics&) override;
|
||||
/** @internal */
|
||||
void resized() override;
|
||||
/** @internal */
|
||||
void mouseWheelMove (const MouseEvent&, const MouseWheelDetails&) override;
|
||||
|
||||
private:
|
||||
//==============================================================================
|
||||
struct UpDownButton;
|
||||
|
||||
Range<float> getKeyPos (int midiNoteNumber) const;
|
||||
NoteAndVelocity remappedXYToNote (Point<float>) const;
|
||||
void setLowestVisibleKeyFloat (float noteNumber);
|
||||
|
||||
//==============================================================================
|
||||
Orientation orientation;
|
||||
|
||||
float blackNoteLengthRatio = 0.7f, blackNoteWidthRatio = 0.7f;
|
||||
float xOffset = 0.0f;
|
||||
float keyWidth = 16.0f;
|
||||
float firstKey = 12 * 4.0f;
|
||||
|
||||
int scrollButtonWidth = 12;
|
||||
int rangeStart = 0, rangeEnd = 127;
|
||||
int octaveNumForMiddleC = 3;
|
||||
|
||||
bool canScroll = true;
|
||||
std::unique_ptr<Button> scrollDown, scrollUp;
|
||||
|
||||
//==============================================================================
|
||||
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (KeyboardComponentBase)
|
||||
};
|
||||
|
||||
} // namespace juce
|
507
deps/juce/modules/juce_audio_utils/gui/juce_MPEKeyboardComponent.cpp
vendored
Normal file
507
deps/juce/modules/juce_audio_utils/gui/juce_MPEKeyboardComponent.cpp
vendored
Normal file
@ -0,0 +1,507 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE library.
|
||||
Copyright (c) 2022 - Raw Material Software Limited
|
||||
|
||||
JUCE is an open source library subject to commercial or open-source
|
||||
licensing.
|
||||
|
||||
By using JUCE, you agree to the terms of both the JUCE 7 End-User License
|
||||
Agreement and JUCE Privacy Policy.
|
||||
|
||||
End User License Agreement: www.juce.com/juce-7-licence
|
||||
Privacy Policy: www.juce.com/juce-privacy-policy
|
||||
|
||||
Or: You may also use this code under the terms of the GPL v3 (see
|
||||
www.gnu.org/licenses).
|
||||
|
||||
JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
|
||||
EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
|
||||
DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
struct MPEKeyboardComponent::MPENoteComponent : public Component
|
||||
{
|
||||
MPENoteComponent (MPEKeyboardComponent& o, uint16 sID, uint8 initial, float noteOnVel, float press)
|
||||
: owner (o),
|
||||
radiusScale (owner.getKeyWidth() / 1.5f),
|
||||
noteOnVelocity (noteOnVel),
|
||||
pressure (press),
|
||||
sourceID (sID),
|
||||
initialNote (initial)
|
||||
{
|
||||
}
|
||||
|
||||
float getStrikeRadius() const { return 5.0f + getNoteOnVelocity() * radiusScale * 2.0f; }
|
||||
float getPressureRadius() const { return 5.0f + getPressure() * radiusScale * 2.0f; }
|
||||
|
||||
float getNoteOnVelocity() const { return noteOnVelocity; }
|
||||
float getPressure() const { return pressure; }
|
||||
|
||||
Point<float> getCentrePos() const { return getBounds().toFloat().getCentre(); }
|
||||
|
||||
void paint (Graphics& g) override
|
||||
{
|
||||
auto strikeSize = getStrikeRadius() * 2.0f;
|
||||
auto pressSize = getPressureRadius() * 2.0f;
|
||||
auto bounds = getLocalBounds().toFloat();
|
||||
|
||||
g.setColour (owner.findColour (noteCircleFillColourId));
|
||||
g.fillEllipse (bounds.withSizeKeepingCentre (strikeSize, strikeSize));
|
||||
|
||||
g.setColour (owner.findColour (noteCircleOutlineColourId));
|
||||
g.drawEllipse (bounds.withSizeKeepingCentre (pressSize, pressSize), 1.0f);
|
||||
}
|
||||
|
||||
//==========================================================================
|
||||
MPEKeyboardComponent& owner;
|
||||
|
||||
float radiusScale = 0.0f, noteOnVelocity = 0.0f, pressure = 0.5f;
|
||||
uint16 sourceID = 0;
|
||||
uint8 initialNote = 0;
|
||||
bool isLatched = true;
|
||||
};
|
||||
|
||||
//==============================================================================
|
||||
MPEKeyboardComponent::MPEKeyboardComponent (MPEInstrument& instr, Orientation orientationToUse)
|
||||
: KeyboardComponentBase (orientationToUse),
|
||||
instrument (instr)
|
||||
{
|
||||
updateZoneLayout();
|
||||
colourChanged();
|
||||
setKeyWidth (25.0f);
|
||||
|
||||
instrument.addListener (this);
|
||||
}
|
||||
|
||||
MPEKeyboardComponent::~MPEKeyboardComponent()
|
||||
{
|
||||
instrument.removeListener (this);
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
void MPEKeyboardComponent::drawKeyboardBackground (Graphics& g, Rectangle<float> area)
|
||||
{
|
||||
g.setColour (findColour (whiteNoteColourId));
|
||||
g.fillRect (area);
|
||||
}
|
||||
|
||||
void MPEKeyboardComponent::drawWhiteKey (int midiNoteNumber, Graphics& g, Rectangle<float> area)
|
||||
{
|
||||
if (midiNoteNumber % 12 == 0)
|
||||
{
|
||||
auto fontHeight = jmin (12.0f, getKeyWidth() * 0.9f);
|
||||
auto text = MidiMessage::getMidiNoteName (midiNoteNumber, true, true, getOctaveForMiddleC());
|
||||
|
||||
g.setColour (findColour (textLabelColourId));
|
||||
g.setFont (Font (fontHeight).withHorizontalScale (0.8f));
|
||||
|
||||
switch (getOrientation())
|
||||
{
|
||||
case horizontalKeyboard:
|
||||
g.drawText (text, area.withTrimmedLeft (1.0f).withTrimmedBottom (2.0f),
|
||||
Justification::centredBottom, false);
|
||||
break;
|
||||
case verticalKeyboardFacingLeft:
|
||||
g.drawText (text, area.reduced (2.0f), Justification::centredLeft, false);
|
||||
break;
|
||||
case verticalKeyboardFacingRight:
|
||||
g.drawText (text, area.reduced (2.0f), Justification::centredRight, false);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void MPEKeyboardComponent::drawBlackKey (int /*midiNoteNumber*/, Graphics& g, Rectangle<float> area)
|
||||
{
|
||||
g.setColour (findColour (whiteNoteColourId));
|
||||
g.fillRect (area);
|
||||
|
||||
g.setColour (findColour (blackNoteColourId));
|
||||
|
||||
if (isHorizontal())
|
||||
{
|
||||
g.fillRoundedRectangle (area.toFloat().reduced ((area.getWidth() / 2.0f) - (getBlackNoteWidth() / 12.0f),
|
||||
area.getHeight() / 4.0f), 1.0f);
|
||||
}
|
||||
else
|
||||
{
|
||||
g.fillRoundedRectangle (area.toFloat().reduced (area.getWidth() / 4.0f,
|
||||
(area.getHeight() / 2.0f) - (getBlackNoteWidth() / 12.0f)), 1.0f);
|
||||
}
|
||||
}
|
||||
|
||||
void MPEKeyboardComponent::colourChanged()
|
||||
{
|
||||
setOpaque (findColour (whiteNoteColourId).isOpaque());
|
||||
repaint();
|
||||
}
|
||||
|
||||
//==========================================================================
|
||||
MPEValue MPEKeyboardComponent::mousePositionToPitchbend (int initialNote, Point<float> mousePos)
|
||||
{
|
||||
auto constrainedMousePos = [&]
|
||||
{
|
||||
auto horizontal = isHorizontal();
|
||||
|
||||
auto posToCheck = jlimit (0.0f,
|
||||
horizontal ? (float) getWidth() - 1.0f : (float) getHeight(),
|
||||
horizontal ? mousePos.x : mousePos.y);
|
||||
|
||||
auto bottomKeyRange = getRectangleForKey (jmax (getRangeStart(), initialNote - perNotePitchbendRange));
|
||||
auto topKeyRange = getRectangleForKey (jmin (getRangeEnd(), initialNote + perNotePitchbendRange));
|
||||
|
||||
auto lowerLimit = horizontal ? bottomKeyRange.getCentreX()
|
||||
: getOrientation() == Orientation::verticalKeyboardFacingRight ? topKeyRange.getCentreY()
|
||||
: bottomKeyRange.getCentreY();
|
||||
|
||||
auto upperLimit = horizontal ? topKeyRange.getCentreX()
|
||||
: getOrientation() == Orientation::verticalKeyboardFacingRight ? bottomKeyRange.getCentreY()
|
||||
: topKeyRange.getCentreY();
|
||||
|
||||
posToCheck = jlimit (lowerLimit, upperLimit, posToCheck);
|
||||
|
||||
return horizontal ? Point<float> (posToCheck, 0.0f)
|
||||
: Point<float> (0.0f, posToCheck);
|
||||
}();
|
||||
|
||||
auto note = getNoteAndVelocityAtPosition (constrainedMousePos, true).note;
|
||||
|
||||
if (note == -1)
|
||||
{
|
||||
jassertfalse;
|
||||
return {};
|
||||
}
|
||||
|
||||
auto fractionalSemitoneBend = [&]
|
||||
{
|
||||
auto noteRect = getRectangleForKey (note);
|
||||
|
||||
switch (getOrientation())
|
||||
{
|
||||
case horizontalKeyboard: return (constrainedMousePos.x - noteRect.getCentreX()) / noteRect.getWidth();
|
||||
case verticalKeyboardFacingRight: return (noteRect.getCentreY() - constrainedMousePos.y) / noteRect.getHeight();
|
||||
case verticalKeyboardFacingLeft: return (constrainedMousePos.y - noteRect.getCentreY()) / noteRect.getHeight();
|
||||
}
|
||||
|
||||
jassertfalse;
|
||||
return 0.0f;
|
||||
}();
|
||||
|
||||
auto totalNumSemitones = ((float) note + fractionalSemitoneBend) - (float) initialNote;
|
||||
|
||||
return MPEValue::fromUnsignedFloat (jmap (totalNumSemitones, (float) -perNotePitchbendRange, (float) perNotePitchbendRange, 0.0f, 1.0f));
|
||||
}
|
||||
|
||||
MPEValue MPEKeyboardComponent::mousePositionToTimbre (Point<float> mousePos)
|
||||
{
|
||||
auto delta = [mousePos, this]
|
||||
{
|
||||
switch (getOrientation())
|
||||
{
|
||||
case horizontalKeyboard: return mousePos.y;
|
||||
case verticalKeyboardFacingLeft: return (float) getWidth() - mousePos.x;
|
||||
case verticalKeyboardFacingRight: return mousePos.x;
|
||||
}
|
||||
|
||||
jassertfalse;
|
||||
return 0.0f;
|
||||
}();
|
||||
|
||||
return MPEValue::fromUnsignedFloat (jlimit (0.0f, 1.0f, 1.0f - (delta / getWhiteNoteLength())));
|
||||
}
|
||||
|
||||
void MPEKeyboardComponent::mouseDown (const MouseEvent& e)
|
||||
{
|
||||
auto newNote = getNoteAndVelocityAtPosition (e.position).note;
|
||||
|
||||
if (newNote >= 0)
|
||||
{
|
||||
auto channel = channelAssigner->findMidiChannelForNewNote (newNote);
|
||||
|
||||
instrument.noteOn (channel, newNote, MPEValue::fromUnsignedFloat (velocity));
|
||||
sourceIDMap[e.source.getIndex()] = instrument.getNote (instrument.getNumPlayingNotes() - 1).noteID;
|
||||
|
||||
instrument.pitchbend (channel, MPEValue::centreValue());
|
||||
instrument.timbre (channel, mousePositionToTimbre (e.position));
|
||||
instrument.pressure (channel, MPEValue::fromUnsignedFloat (e.isPressureValid()
|
||||
&& useMouseSourcePressureForStrike ? e.pressure
|
||||
: pressure));
|
||||
}
|
||||
}
|
||||
|
||||
void MPEKeyboardComponent::mouseDrag (const MouseEvent& e)
|
||||
{
|
||||
auto noteID = sourceIDMap[e.source.getIndex()];
|
||||
auto note = instrument.getNoteWithID (noteID);
|
||||
|
||||
if (! note.isValid())
|
||||
return;
|
||||
|
||||
auto noteComponent = std::find_if (noteComponents.begin(),
|
||||
noteComponents.end(),
|
||||
[noteID] (auto& comp) { return comp->sourceID == noteID; });
|
||||
|
||||
if (noteComponent == noteComponents.end())
|
||||
return;
|
||||
|
||||
if ((*noteComponent)->isLatched && std::abs (isHorizontal() ? e.getDistanceFromDragStartX()
|
||||
: e.getDistanceFromDragStartY()) > roundToInt (getKeyWidth() / 4.0f))
|
||||
{
|
||||
(*noteComponent)->isLatched = false;
|
||||
}
|
||||
|
||||
auto channel = channelAssigner->findMidiChannelForExistingNote (note.initialNote);
|
||||
|
||||
if (! (*noteComponent)->isLatched)
|
||||
instrument.pitchbend (channel, mousePositionToPitchbend (note.initialNote, e.position));
|
||||
|
||||
instrument.timbre (channel, mousePositionToTimbre (e.position));
|
||||
instrument.pressure (channel, MPEValue::fromUnsignedFloat (e.isPressureValid()
|
||||
&& useMouseSourcePressureForStrike ? e.pressure
|
||||
: pressure));
|
||||
}
|
||||
|
||||
void MPEKeyboardComponent::mouseUp (const MouseEvent& e)
|
||||
{
|
||||
auto note = instrument.getNoteWithID (sourceIDMap[e.source.getIndex()]);
|
||||
|
||||
if (! note.isValid())
|
||||
return;
|
||||
|
||||
instrument.noteOff (channelAssigner->findMidiChannelForExistingNote (note.initialNote),
|
||||
note.initialNote, MPEValue::fromUnsignedFloat (lift));
|
||||
channelAssigner->noteOff (note.initialNote);
|
||||
sourceIDMap.erase (e.source.getIndex());
|
||||
}
|
||||
|
||||
void MPEKeyboardComponent::focusLost (FocusChangeType)
|
||||
{
|
||||
for (auto& comp : noteComponents)
|
||||
{
|
||||
auto note = instrument.getNoteWithID (comp->sourceID);
|
||||
|
||||
if (note.isValid())
|
||||
instrument.noteOff (channelAssigner->findMidiChannelForExistingNote (note.initialNote),
|
||||
note.initialNote, MPEValue::fromUnsignedFloat (lift));
|
||||
}
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
void MPEKeyboardComponent::updateZoneLayout()
|
||||
{
|
||||
{
|
||||
const ScopedLock noteLock (activeNotesLock);
|
||||
activeNotes.clear();
|
||||
}
|
||||
|
||||
noteComponents.clear();
|
||||
|
||||
if (instrument.isLegacyModeEnabled())
|
||||
{
|
||||
channelAssigner = std::make_unique<MPEChannelAssigner> (instrument.getLegacyModeChannelRange());
|
||||
perNotePitchbendRange = instrument.getLegacyModePitchbendRange();
|
||||
}
|
||||
else
|
||||
{
|
||||
auto layout = instrument.getZoneLayout();
|
||||
|
||||
if (layout.isActive())
|
||||
{
|
||||
auto zone = layout.getLowerZone().isActive() ? layout.getLowerZone()
|
||||
: layout.getUpperZone();
|
||||
|
||||
channelAssigner = std::make_unique<MPEChannelAssigner> (zone);
|
||||
perNotePitchbendRange = zone.perNotePitchbendRange;
|
||||
}
|
||||
else
|
||||
{
|
||||
channelAssigner.reset();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void MPEKeyboardComponent::addNewNote (MPENote note)
|
||||
{
|
||||
noteComponents.push_back (std::make_unique<MPENoteComponent> (*this, note.noteID, note.initialNote,
|
||||
note.noteOnVelocity.asUnsignedFloat(),
|
||||
note.pressure.asUnsignedFloat()));
|
||||
auto& comp = noteComponents.back();
|
||||
|
||||
addAndMakeVisible (*comp);
|
||||
comp->toBack();
|
||||
}
|
||||
|
||||
void MPEKeyboardComponent::handleNoteOns (std::set<MPENote>& notesToUpdate)
|
||||
{
|
||||
for (auto& note : notesToUpdate)
|
||||
{
|
||||
if (! std::any_of (noteComponents.begin(),
|
||||
noteComponents.end(),
|
||||
[note] (auto& comp) { return comp->sourceID == note.noteID; }))
|
||||
{
|
||||
addNewNote (note);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void MPEKeyboardComponent::handleNoteOffs (std::set<MPENote>& notesToUpdate)
|
||||
{
|
||||
auto removePredicate = [¬esToUpdate] (std::unique_ptr<MPENoteComponent>& comp)
|
||||
{
|
||||
return std::none_of (notesToUpdate.begin(),
|
||||
notesToUpdate.end(),
|
||||
[&comp] (auto& note) { return comp->sourceID == note.noteID; });
|
||||
};
|
||||
|
||||
noteComponents.erase (std::remove_if (std::begin (noteComponents),
|
||||
std::end (noteComponents),
|
||||
removePredicate),
|
||||
std::end (noteComponents));
|
||||
|
||||
if (noteComponents.empty())
|
||||
stopTimer();
|
||||
}
|
||||
|
||||
void MPEKeyboardComponent::updateNoteComponentBounds (const MPENote& note, MPENoteComponent& noteComponent)
|
||||
{
|
||||
auto xPos = [&]
|
||||
{
|
||||
const auto currentNote = note.initialNote + (float) note.totalPitchbendInSemitones;
|
||||
const auto noteBend = currentNote - std::floor (currentNote);
|
||||
|
||||
const auto noteBounds = getRectangleForKey ((int) currentNote);
|
||||
const auto nextNoteBounds = getRectangleForKey ((int) currentNote + 1);
|
||||
|
||||
const auto horizontal = isHorizontal();
|
||||
|
||||
const auto distance = noteBend * (horizontal ? nextNoteBounds.getCentreX() - noteBounds.getCentreX()
|
||||
: nextNoteBounds.getCentreY() - noteBounds.getCentreY());
|
||||
|
||||
return (horizontal ? noteBounds.getCentreX() : noteBounds.getCentreY()) + distance;
|
||||
}();
|
||||
|
||||
auto yPos = [&]
|
||||
{
|
||||
const auto currentOrientation = getOrientation();
|
||||
|
||||
const auto timbrePosition = (currentOrientation == horizontalKeyboard
|
||||
|| currentOrientation == verticalKeyboardFacingRight ? 1.0f - note.timbre.asUnsignedFloat()
|
||||
: note.timbre.asUnsignedFloat());
|
||||
|
||||
return timbrePosition * getWhiteNoteLength();
|
||||
}();
|
||||
|
||||
const auto centrePos = (isHorizontal() ? Point<float> (xPos, yPos)
|
||||
: Point<float> (yPos, xPos));
|
||||
|
||||
const auto radius = jmax (noteComponent.getStrikeRadius(), noteComponent.getPressureRadius());
|
||||
|
||||
noteComponent.setBounds (Rectangle<float> (radius * 2.0f, radius * 2.0f)
|
||||
.withCentre (centrePos)
|
||||
.getSmallestIntegerContainer());
|
||||
}
|
||||
|
||||
static bool operator< (const MPENote& n1, const MPENote& n2) noexcept { return n1.noteID < n2.noteID; }
|
||||
|
||||
void MPEKeyboardComponent::updateNoteComponents()
|
||||
{
|
||||
std::set<MPENote> notesToUpdate;
|
||||
|
||||
{
|
||||
ScopedLock noteLock (activeNotesLock);
|
||||
|
||||
for (const auto& note : activeNotes)
|
||||
if (note.second)
|
||||
notesToUpdate.insert (note.first);
|
||||
};
|
||||
|
||||
handleNoteOns (notesToUpdate);
|
||||
handleNoteOffs (notesToUpdate);
|
||||
|
||||
for (auto& comp : noteComponents)
|
||||
{
|
||||
auto noteForComponent = std::find_if (notesToUpdate.begin(),
|
||||
notesToUpdate.end(),
|
||||
[&comp] (auto& note) { return note.noteID == comp->sourceID; });
|
||||
|
||||
if (noteForComponent != notesToUpdate.end())
|
||||
{
|
||||
comp->pressure = noteForComponent->pressure.asUnsignedFloat();
|
||||
updateNoteComponentBounds (*noteForComponent, *comp);
|
||||
|
||||
comp->repaint();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void MPEKeyboardComponent::timerCallback()
|
||||
{
|
||||
updateNoteComponents();
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
void MPEKeyboardComponent::noteAdded (MPENote newNote)
|
||||
{
|
||||
{
|
||||
const ScopedLock noteLock (activeNotesLock);
|
||||
activeNotes.push_back ({ newNote, true });
|
||||
}
|
||||
|
||||
startTimerHz (30);
|
||||
}
|
||||
|
||||
void MPEKeyboardComponent::updateNoteData (MPENote& changedNote)
|
||||
{
|
||||
const ScopedLock noteLock (activeNotesLock);
|
||||
|
||||
for (auto& note : activeNotes)
|
||||
{
|
||||
if (note.first.noteID == changedNote.noteID)
|
||||
{
|
||||
note.first = changedNote;
|
||||
note.second = true;
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void MPEKeyboardComponent::notePressureChanged (MPENote changedNote)
|
||||
{
|
||||
updateNoteData (changedNote);
|
||||
}
|
||||
|
||||
void MPEKeyboardComponent::notePitchbendChanged (MPENote changedNote)
|
||||
{
|
||||
updateNoteData (changedNote);
|
||||
}
|
||||
|
||||
void MPEKeyboardComponent::noteTimbreChanged (MPENote changedNote)
|
||||
{
|
||||
updateNoteData (changedNote);
|
||||
}
|
||||
|
||||
void MPEKeyboardComponent::noteReleased (MPENote finishedNote)
|
||||
{
|
||||
const ScopedLock noteLock (activeNotesLock);
|
||||
|
||||
activeNotes.erase (std::remove_if (std::begin (activeNotes),
|
||||
std::end (activeNotes),
|
||||
[finishedNote] (auto& note) { return note.first.noteID == finishedNote.noteID; }),
|
||||
std::end (activeNotes));
|
||||
}
|
||||
|
||||
void MPEKeyboardComponent::zoneLayoutChanged()
|
||||
{
|
||||
MessageManager::callAsync ([this] { updateZoneLayout(); });
|
||||
}
|
||||
|
||||
} // namespace juce
|
153
deps/juce/modules/juce_audio_utils/gui/juce_MPEKeyboardComponent.h
vendored
Normal file
153
deps/juce/modules/juce_audio_utils/gui/juce_MPEKeyboardComponent.h
vendored
Normal file
@ -0,0 +1,153 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE library.
|
||||
Copyright (c) 2022 - Raw Material Software Limited
|
||||
|
||||
JUCE is an open source library subject to commercial or open-source
|
||||
licensing.
|
||||
|
||||
By using JUCE, you agree to the terms of both the JUCE 7 End-User License
|
||||
Agreement and JUCE Privacy Policy.
|
||||
|
||||
End User License Agreement: www.juce.com/juce-7-licence
|
||||
Privacy Policy: www.juce.com/juce-privacy-policy
|
||||
|
||||
Or: You may also use this code under the terms of the GPL v3 (see
|
||||
www.gnu.org/licenses).
|
||||
|
||||
JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
|
||||
EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
|
||||
DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
//==============================================================================
|
||||
/**
|
||||
A component that displays an MPE-compatible keyboard, whose notes can be clicked on.
|
||||
|
||||
This component will mimic a physical MPE-compatible keyboard, showing the current state
|
||||
of an MPEInstrument object. When the on-screen keys are clicked on, it will play these
|
||||
notes by calling the noteOn() and noteOff() methods of its MPEInstrument object. Moving
|
||||
the mouse will update the pitchbend and timbre dimensions of the MPEInstrument.
|
||||
|
||||
@see MPEInstrument
|
||||
|
||||
@tags{Audio}
|
||||
*/
|
||||
class JUCE_API MPEKeyboardComponent : public KeyboardComponentBase,
|
||||
private MPEInstrument::Listener,
|
||||
private Timer
|
||||
{
|
||||
public:
|
||||
//==============================================================================
|
||||
/** Creates an MPEKeyboardComponent.
|
||||
|
||||
@param instrument the MPEInstrument that this component represents
|
||||
@param orientation whether the keyboard is horizontal or vertical
|
||||
*/
|
||||
MPEKeyboardComponent (MPEInstrument& instrument, Orientation orientation);
|
||||
|
||||
/** Destructor. */
|
||||
virtual ~MPEKeyboardComponent() override;
|
||||
|
||||
//==============================================================================
|
||||
/** Sets the note-on velocity, or "strike", value that will be used when triggering new notes. */
|
||||
void setVelocity (float newVelocity) { velocity = jlimit (newVelocity, 0.0f, 1.0f); }
|
||||
|
||||
/** Sets the pressure value that will be used for new notes. */
|
||||
void setPressure (float newPressure) { pressure = jlimit (newPressure, 0.0f, 1.0f); }
|
||||
|
||||
/** Sets the note-off velocity, or "lift", value that will be used when notes are released. */
|
||||
void setLift (float newLift) { lift = jlimit (newLift, 0.0f, 1.0f); }
|
||||
|
||||
/** Use this to enable the mouse source pressure to be used for the initial note-on
|
||||
velocity, or "strike", value if the mouse source supports it.
|
||||
*/
|
||||
void setUseMouseSourcePressureForStrike (bool usePressureForStrike) { useMouseSourcePressureForStrike = usePressureForStrike; }
|
||||
|
||||
//==============================================================================
|
||||
/** A set of colour IDs to use to change the colour of various aspects of the keyboard.
|
||||
|
||||
These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
|
||||
methods.
|
||||
|
||||
@see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
|
||||
*/
|
||||
enum ColourIds
|
||||
{
|
||||
whiteNoteColourId = 0x1006000,
|
||||
blackNoteColourId = 0x1006001,
|
||||
textLabelColourId = 0x1006002,
|
||||
noteCircleFillColourId = 0x1006003,
|
||||
noteCircleOutlineColourId = 0x1006004
|
||||
};
|
||||
|
||||
//==============================================================================
|
||||
/** @internal */
|
||||
void mouseDrag (const MouseEvent&) override;
|
||||
/** @internal */
|
||||
void mouseDown (const MouseEvent&) override;
|
||||
/** @internal */
|
||||
void mouseUp (const MouseEvent&) override;
|
||||
/** @internal */
|
||||
void focusLost (FocusChangeType) override;
|
||||
/** @internal */
|
||||
void colourChanged() override;
|
||||
|
||||
private:
|
||||
//==========================================================================
|
||||
struct MPENoteComponent;
|
||||
|
||||
//==============================================================================
|
||||
void drawKeyboardBackground (Graphics& g, Rectangle<float> area) override;
|
||||
void drawWhiteKey (int midiNoteNumber, Graphics& g, Rectangle<float> area) override;
|
||||
void drawBlackKey (int midiNoteNumber, Graphics& g, Rectangle<float> area) override;
|
||||
|
||||
void updateNoteData (MPENote&);
|
||||
|
||||
void noteAdded (MPENote) override;
|
||||
void notePressureChanged (MPENote) override;
|
||||
void notePitchbendChanged (MPENote) override;
|
||||
void noteTimbreChanged (MPENote) override;
|
||||
void noteReleased (MPENote) override;
|
||||
void zoneLayoutChanged() override;
|
||||
|
||||
void timerCallback() override;
|
||||
|
||||
//==============================================================================
|
||||
MPEValue mousePositionToPitchbend (int, Point<float>);
|
||||
MPEValue mousePositionToTimbre (Point<float>);
|
||||
|
||||
void addNewNote (MPENote);
|
||||
void removeNote (MPENote);
|
||||
|
||||
void handleNoteOns (std::set<MPENote>&);
|
||||
void handleNoteOffs (std::set<MPENote>&);
|
||||
void updateNoteComponentBounds (const MPENote&, MPENoteComponent&);
|
||||
void updateNoteComponents();
|
||||
|
||||
void updateZoneLayout();
|
||||
|
||||
//==============================================================================
|
||||
MPEInstrument& instrument;
|
||||
std::unique_ptr<MPEChannelAssigner> channelAssigner;
|
||||
|
||||
CriticalSection activeNotesLock;
|
||||
std::vector<std::pair<MPENote, bool>> activeNotes;
|
||||
std::vector<std::unique_ptr<MPENoteComponent>> noteComponents;
|
||||
std::map<int, uint16> sourceIDMap;
|
||||
|
||||
float velocity = 0.7f, pressure = 1.0f, lift = 0.0f;
|
||||
bool useMouseSourcePressureForStrike = false;
|
||||
int perNotePitchbendRange = 48;
|
||||
|
||||
//==============================================================================
|
||||
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MPEKeyboardComponent)
|
||||
};
|
||||
|
||||
} // namespace juce
|
File diff suppressed because it is too large
Load Diff
@ -1,445 +1,279 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE library.
|
||||
Copyright (c) 2020 - Raw Material Software Limited
|
||||
|
||||
JUCE is an open source library subject to commercial or open-source
|
||||
licensing.
|
||||
|
||||
By using JUCE, you agree to the terms of both the JUCE 6 End-User License
|
||||
Agreement and JUCE Privacy Policy (both effective as of the 16th June 2020).
|
||||
|
||||
End User License Agreement: www.juce.com/juce-6-licence
|
||||
Privacy Policy: www.juce.com/juce-privacy-policy
|
||||
|
||||
Or: You may also use this code under the terms of the GPL v3 (see
|
||||
www.gnu.org/licenses).
|
||||
|
||||
JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
|
||||
EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
|
||||
DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
//==============================================================================
|
||||
/**
|
||||
A component that displays a piano keyboard, whose notes can be clicked on.
|
||||
|
||||
This component will mimic a physical midi keyboard, showing the current state of
|
||||
a MidiKeyboardState object. When the on-screen keys are clicked on, it will play these
|
||||
notes by calling the noteOn() and noteOff() methods of its MidiKeyboardState object.
|
||||
|
||||
Another feature is that the computer keyboard can also be used to play notes. By
|
||||
default it maps the top two rows of a standard qwerty keyboard to the notes, but
|
||||
these can be remapped if needed. It will only respond to keypresses when it has
|
||||
the keyboard focus, so to disable this feature you can call setWantsKeyboardFocus (false).
|
||||
|
||||
The component is also a ChangeBroadcaster, so if you want to be informed when the
|
||||
keyboard is scrolled, you can register a ChangeListener for callbacks.
|
||||
|
||||
@see MidiKeyboardState
|
||||
|
||||
@tags{Audio}
|
||||
*/
|
||||
class JUCE_API MidiKeyboardComponent : public Component,
|
||||
public MidiKeyboardState::Listener,
|
||||
public ChangeBroadcaster,
|
||||
private Timer
|
||||
{
|
||||
public:
|
||||
//==============================================================================
|
||||
/** The direction of the keyboard.
|
||||
@see setOrientation
|
||||
*/
|
||||
enum Orientation
|
||||
{
|
||||
horizontalKeyboard,
|
||||
verticalKeyboardFacingLeft,
|
||||
verticalKeyboardFacingRight,
|
||||
};
|
||||
|
||||
/** Creates a MidiKeyboardComponent.
|
||||
|
||||
@param state the midi keyboard model that this component will represent
|
||||
@param orientation whether the keyboard is horizontal or vertical
|
||||
*/
|
||||
MidiKeyboardComponent (MidiKeyboardState& state,
|
||||
Orientation orientation);
|
||||
|
||||
/** Destructor. */
|
||||
~MidiKeyboardComponent() override;
|
||||
|
||||
//==============================================================================
|
||||
/** Changes the velocity used in midi note-on messages that are triggered by clicking
|
||||
on the component.
|
||||
|
||||
Values are 0 to 1.0, where 1.0 is the heaviest.
|
||||
|
||||
@see setMidiChannel
|
||||
*/
|
||||
void setVelocity (float velocity, bool useMousePositionForVelocity);
|
||||
|
||||
/** Changes the midi channel number that will be used for events triggered by clicking
|
||||
on the component.
|
||||
|
||||
The channel must be between 1 and 16 (inclusive). This is the channel that will be
|
||||
passed on to the MidiKeyboardState::noteOn() method when the user clicks the component.
|
||||
|
||||
Although this is the channel used for outgoing events, the component can display
|
||||
incoming events from more than one channel - see setMidiChannelsToDisplay()
|
||||
|
||||
@see setVelocity
|
||||
*/
|
||||
void setMidiChannel (int midiChannelNumber);
|
||||
|
||||
/** Returns the midi channel that the keyboard is using for midi messages.
|
||||
@see setMidiChannel
|
||||
*/
|
||||
int getMidiChannel() const noexcept { return midiChannel; }
|
||||
|
||||
/** Sets a mask to indicate which incoming midi channels should be represented by
|
||||
key movements.
|
||||
|
||||
The mask is a set of bits, where bit 0 = midi channel 1, bit 1 = midi channel 2, etc.
|
||||
|
||||
If the MidiKeyboardState has a key down for any of the channels whose bits are set
|
||||
in this mask, the on-screen keys will also go down.
|
||||
|
||||
By default, this mask is set to 0xffff (all channels displayed).
|
||||
|
||||
@see setMidiChannel
|
||||
*/
|
||||
void setMidiChannelsToDisplay (int midiChannelMask);
|
||||
|
||||
/** Returns the current set of midi channels represented by the component.
|
||||
This is the value that was set with setMidiChannelsToDisplay().
|
||||
*/
|
||||
int getMidiChannelsToDisplay() const noexcept { return midiInChannelMask; }
|
||||
|
||||
//==============================================================================
|
||||
/** Changes the width used to draw the white keys. */
|
||||
void setKeyWidth (float widthInPixels);
|
||||
|
||||
/** Returns the width that was set by setKeyWidth(). */
|
||||
float getKeyWidth() const noexcept { return keyWidth; }
|
||||
|
||||
/** Changes the width used to draw the buttons that scroll the keyboard up/down in octaves. */
|
||||
void setScrollButtonWidth (int widthInPixels);
|
||||
|
||||
/** Returns the width that was set by setScrollButtonWidth(). */
|
||||
int getScrollButtonWidth() const noexcept { return scrollButtonWidth; }
|
||||
|
||||
/** Changes the keyboard's current direction. */
|
||||
void setOrientation (Orientation newOrientation);
|
||||
|
||||
/** Returns the keyboard's current direction. */
|
||||
Orientation getOrientation() const noexcept { return orientation; }
|
||||
|
||||
/** Sets the range of midi notes that the keyboard will be limited to.
|
||||
|
||||
By default the range is 0 to 127 (inclusive), but you can limit this if you
|
||||
only want a restricted set of the keys to be shown.
|
||||
|
||||
Note that the values here are inclusive and must be between 0 and 127.
|
||||
*/
|
||||
void setAvailableRange (int lowestNote,
|
||||
int highestNote);
|
||||
|
||||
/** Returns the first note in the available range.
|
||||
@see setAvailableRange
|
||||
*/
|
||||
int getRangeStart() const noexcept { return rangeStart; }
|
||||
|
||||
/** Returns the last note in the available range.
|
||||
@see setAvailableRange
|
||||
*/
|
||||
int getRangeEnd() const noexcept { return rangeEnd; }
|
||||
|
||||
/** If the keyboard extends beyond the size of the component, this will scroll
|
||||
it to show the given key at the start.
|
||||
|
||||
Whenever the keyboard's position is changed, this will use the ChangeBroadcaster
|
||||
base class to send a callback to any ChangeListeners that have been registered.
|
||||
*/
|
||||
void setLowestVisibleKey (int noteNumber);
|
||||
|
||||
/** Returns the number of the first key shown in the component.
|
||||
@see setLowestVisibleKey
|
||||
*/
|
||||
int getLowestVisibleKey() const noexcept { return (int) firstKey; }
|
||||
|
||||
/** Sets the length of the black notes as a proportion of the white note length. */
|
||||
void setBlackNoteLengthProportion (float ratio) noexcept;
|
||||
|
||||
/** Returns the length of the black notes as a proportion of the white note length. */
|
||||
float getBlackNoteLengthProportion() const noexcept { return blackNoteLengthRatio; }
|
||||
|
||||
/** Returns the absolute length of the black notes.
|
||||
This will be their vertical or horizontal length, depending on the keyboard's orientation.
|
||||
*/
|
||||
float getBlackNoteLength() const noexcept;
|
||||
|
||||
/** Sets the width of the black notes as a proportion of the white note width. */
|
||||
void setBlackNoteWidthProportion (float ratio) noexcept;
|
||||
|
||||
/** Returns the width of the black notes as a proportion of the white note width. */
|
||||
float getBlackNoteWidthProportion() const noexcept { return blackNoteWidthRatio; }
|
||||
|
||||
/** Returns the absolute width of the black notes.
|
||||
This will be their vertical or horizontal width, depending on the keyboard's orientation.
|
||||
*/
|
||||
float getBlackNoteWidth() const noexcept { return keyWidth * blackNoteWidthRatio; }
|
||||
|
||||
/** If set to true, then scroll buttons will appear at either end of the keyboard
|
||||
if there are too many notes to fit them all in the component at once.
|
||||
*/
|
||||
void setScrollButtonsVisible (bool canScroll);
|
||||
|
||||
/** Sets width of scroll buttons */
|
||||
void setScrollButtonsWidth (int width);
|
||||
|
||||
/** Returns width of scroll buttons */
|
||||
int getScrollButtonsWidth () const { return scrollButtonWidth; }
|
||||
|
||||
//==============================================================================
|
||||
/** A set of colour IDs to use to change the colour of various aspects of the keyboard.
|
||||
|
||||
These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
|
||||
methods.
|
||||
|
||||
@see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
|
||||
*/
|
||||
enum ColourIds
|
||||
{
|
||||
whiteNoteColourId = 0x1005000,
|
||||
blackNoteColourId = 0x1005001,
|
||||
keySeparatorLineColourId = 0x1005002,
|
||||
mouseOverKeyOverlayColourId = 0x1005003, /**< This colour will be overlaid on the normal note colour. */
|
||||
keyDownOverlayColourId = 0x1005004, /**< This colour will be overlaid on the normal note colour. */
|
||||
textLabelColourId = 0x1005005,
|
||||
upDownButtonBackgroundColourId = 0x1005006,
|
||||
upDownButtonArrowColourId = 0x1005007,
|
||||
shadowColourId = 0x1005008
|
||||
};
|
||||
|
||||
/** Returns the position within the component of the left-hand edge of a key.
|
||||
|
||||
Depending on the keyboard's orientation, this may be a horizontal or vertical
|
||||
distance, in either direction.
|
||||
*/
|
||||
float getKeyStartPosition (int midiNoteNumber) const;
|
||||
|
||||
/** Returns the total width needed to fit all the keys in the available range. */
|
||||
float getTotalKeyboardWidth() const noexcept;
|
||||
|
||||
/** Returns the key at a given coordinate. */
|
||||
int getNoteAtPosition (Point<float> position);
|
||||
|
||||
//==============================================================================
|
||||
/** Deletes all key-mappings.
|
||||
@see setKeyPressForNote
|
||||
*/
|
||||
void clearKeyMappings();
|
||||
|
||||
/** Maps a key-press to a given note.
|
||||
|
||||
@param key the key that should trigger the note
|
||||
@param midiNoteOffsetFromC how many semitones above C the triggered note should
|
||||
be. The actual midi note that gets played will be
|
||||
this value + (12 * the current base octave). To change
|
||||
the base octave, see setKeyPressBaseOctave()
|
||||
*/
|
||||
void setKeyPressForNote (const KeyPress& key,
|
||||
int midiNoteOffsetFromC);
|
||||
|
||||
/** Removes any key-mappings for a given note.
|
||||
For a description of what the note number means, see setKeyPressForNote().
|
||||
*/
|
||||
void removeKeyPressForNote (int midiNoteOffsetFromC);
|
||||
|
||||
/** Changes the base note above which key-press-triggered notes are played.
|
||||
|
||||
The set of key-mappings that trigger notes can be moved up and down to cover
|
||||
the entire scale using this method.
|
||||
|
||||
The value passed in is an octave number between 0 and 10 (inclusive), and
|
||||
indicates which C is the base note to which the key-mapped notes are
|
||||
relative.
|
||||
*/
|
||||
void setKeyPressBaseOctave (int newOctaveNumber);
|
||||
|
||||
/** This sets the octave number which is shown as the octave number for middle C.
|
||||
|
||||
This affects only the default implementation of getWhiteNoteText(), which
|
||||
passes this octave number to MidiMessage::getMidiNoteName() in order to
|
||||
get the note text. See MidiMessage::getMidiNoteName() for more info about
|
||||
the parameter.
|
||||
|
||||
By default this value is set to 3.
|
||||
|
||||
@see getOctaveForMiddleC
|
||||
*/
|
||||
void setOctaveForMiddleC (int octaveNumForMiddleC);
|
||||
|
||||
/** This returns the value set by setOctaveForMiddleC().
|
||||
@see setOctaveForMiddleC
|
||||
*/
|
||||
int getOctaveForMiddleC() const noexcept { return octaveNumForMiddleC; }
|
||||
|
||||
//==============================================================================
|
||||
/** @internal */
|
||||
void paint (Graphics&) override;
|
||||
/** @internal */
|
||||
void resized() override;
|
||||
/** @internal */
|
||||
void mouseMove (const MouseEvent&) override;
|
||||
/** @internal */
|
||||
void mouseDrag (const MouseEvent&) override;
|
||||
/** @internal */
|
||||
void mouseDown (const MouseEvent&) override;
|
||||
/** @internal */
|
||||
void mouseUp (const MouseEvent&) override;
|
||||
/** @internal */
|
||||
void mouseEnter (const MouseEvent&) override;
|
||||
/** @internal */
|
||||
void mouseExit (const MouseEvent&) override;
|
||||
/** @internal */
|
||||
void mouseWheelMove (const MouseEvent&, const MouseWheelDetails&) override;
|
||||
/** @internal */
|
||||
void timerCallback() override;
|
||||
/** @internal */
|
||||
bool keyStateChanged (bool isKeyDown) override;
|
||||
/** @internal */
|
||||
bool keyPressed (const KeyPress&) override;
|
||||
/** @internal */
|
||||
void focusLost (FocusChangeType) override;
|
||||
/** @internal */
|
||||
void handleNoteOn (MidiKeyboardState*, int midiChannel, int midiNoteNumber, float velocity) override;
|
||||
/** @internal */
|
||||
void handleNoteOff (MidiKeyboardState*, int midiChannel, int midiNoteNumber, float velocity) override;
|
||||
/** @internal */
|
||||
void colourChanged() override;
|
||||
|
||||
protected:
|
||||
//==============================================================================
|
||||
/** Draws a white note in the given rectangle.
|
||||
|
||||
isOver indicates whether the mouse is over the key, isDown indicates whether the key is
|
||||
currently pressed down.
|
||||
|
||||
When doing this, be sure to note the keyboard's orientation.
|
||||
*/
|
||||
virtual void drawWhiteNote (int midiNoteNumber,
|
||||
Graphics& g, Rectangle<float> area,
|
||||
bool isDown, bool isOver,
|
||||
Colour lineColour, Colour textColour);
|
||||
|
||||
/** Draws a black note in the given rectangle.
|
||||
|
||||
isOver indicates whether the mouse is over the key, isDown indicates whether the key is
|
||||
currently pressed down.
|
||||
|
||||
When doing this, be sure to note the keyboard's orientation.
|
||||
*/
|
||||
virtual void drawBlackNote (int midiNoteNumber,
|
||||
Graphics& g, Rectangle<float> area,
|
||||
bool isDown, bool isOver,
|
||||
Colour noteFillColour);
|
||||
|
||||
/** Allows text to be drawn on the white notes.
|
||||
By default this is used to label the C in each octave, but could be used for other things.
|
||||
@see setOctaveForMiddleC
|
||||
*/
|
||||
virtual String getWhiteNoteText (int midiNoteNumber);
|
||||
|
||||
/** Draws the up and down buttons that scroll the keyboard up/down in octaves. */
|
||||
virtual void drawUpDownButton (Graphics& g, int w, int h,
|
||||
bool isMouseOver,
|
||||
bool isButtonPressed,
|
||||
bool movesOctavesUp);
|
||||
|
||||
/** Callback when the mouse is clicked on a key.
|
||||
|
||||
You could use this to do things like handle right-clicks on keys, etc.
|
||||
|
||||
Return true if you want the click to trigger the note, or false if you
|
||||
want to handle it yourself and not have the note played.
|
||||
|
||||
@see mouseDraggedToKey
|
||||
*/
|
||||
virtual bool mouseDownOnKey (int midiNoteNumber, const MouseEvent& e);
|
||||
|
||||
/** Callback when the mouse is dragged from one key onto another.
|
||||
|
||||
Return true if you want the drag to trigger the new note, or false if you
|
||||
want to handle it yourself and not have the note played.
|
||||
|
||||
@see mouseDownOnKey
|
||||
*/
|
||||
virtual bool mouseDraggedToKey (int midiNoteNumber, const MouseEvent& e);
|
||||
|
||||
/** Callback when the mouse is released from a key.
|
||||
@see mouseDownOnKey
|
||||
*/
|
||||
virtual void mouseUpOnKey (int midiNoteNumber, const MouseEvent& e);
|
||||
|
||||
/** Calculates the position of a given midi-note.
|
||||
|
||||
This can be overridden to create layouts with custom key-widths.
|
||||
|
||||
@param midiNoteNumber the note to find
|
||||
@param keyWidth the desired width in pixels of one key - see setKeyWidth()
|
||||
@returns the start and length of the key along the axis of the keyboard
|
||||
*/
|
||||
virtual Range<float> getKeyPosition (int midiNoteNumber, float keyWidth) const;
|
||||
|
||||
/** Returns the rectangle for a given key if within the displayable range */
|
||||
Rectangle<float> getRectangleForKey (int midiNoteNumber) const;
|
||||
|
||||
|
||||
private:
|
||||
//==============================================================================
|
||||
struct UpDownButton;
|
||||
|
||||
MidiKeyboardState& state;
|
||||
float blackNoteLengthRatio = 0.7f;
|
||||
float blackNoteWidthRatio = 0.7f;
|
||||
float xOffset = 0;
|
||||
float keyWidth = 16.0f;
|
||||
int scrollButtonWidth = 12;
|
||||
Orientation orientation;
|
||||
|
||||
int midiChannel = 1, midiInChannelMask = 0xffff;
|
||||
float velocity = 1.0f;
|
||||
|
||||
Array<int> mouseOverNotes, mouseDownNotes;
|
||||
BigInteger keysPressed, keysCurrentlyDrawnDown;
|
||||
std::atomic<bool> noPendingUpdates { true };
|
||||
|
||||
int rangeStart = 0, rangeEnd = 127;
|
||||
float firstKey = 12 * 4.0f;
|
||||
bool canScroll = true, useMousePositionForVelocity = true;
|
||||
std::unique_ptr<Button> scrollDown, scrollUp;
|
||||
|
||||
Array<KeyPress> keyPresses;
|
||||
Array<int> keyPressNotes;
|
||||
int keyMappingOctave = 6, octaveNumForMiddleC = 3;
|
||||
|
||||
Range<float> getKeyPos (int midiNoteNumber) const;
|
||||
int xyToNote (Point<float>, float& mousePositionVelocity);
|
||||
int remappedXYToNote (Point<float>, float& mousePositionVelocity) const;
|
||||
void resetAnyKeysInUse();
|
||||
void updateNoteUnderMouse (Point<float>, bool isDown, int fingerNum);
|
||||
void updateNoteUnderMouse (const MouseEvent&, bool isDown);
|
||||
void repaintNote (int midiNoteNumber);
|
||||
void setLowestVisibleKeyFloat (float noteNumber);
|
||||
|
||||
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiKeyboardComponent)
|
||||
};
|
||||
|
||||
} // namespace juce
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE library.
|
||||
Copyright (c) 2022 - Raw Material Software Limited
|
||||
|
||||
JUCE is an open source library subject to commercial or open-source
|
||||
licensing.
|
||||
|
||||
By using JUCE, you agree to the terms of both the JUCE 7 End-User License
|
||||
Agreement and JUCE Privacy Policy.
|
||||
|
||||
End User License Agreement: www.juce.com/juce-7-licence
|
||||
Privacy Policy: www.juce.com/juce-privacy-policy
|
||||
|
||||
Or: You may also use this code under the terms of the GPL v3 (see
|
||||
www.gnu.org/licenses).
|
||||
|
||||
JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
|
||||
EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
|
||||
DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
//==============================================================================
|
||||
/**
|
||||
A component that displays a piano keyboard, whose notes can be clicked on.
|
||||
|
||||
This component will mimic a physical midi keyboard, showing the current state of
|
||||
a MidiKeyboardState object. When the on-screen keys are clicked on, it will play these
|
||||
notes by calling the noteOn() and noteOff() methods of its MidiKeyboardState object.
|
||||
|
||||
Another feature is that the computer keyboard can also be used to play notes. By
|
||||
default it maps the top two rows of a standard qwerty keyboard to the notes, but
|
||||
these can be remapped if needed. It will only respond to keypresses when it has
|
||||
the keyboard focus, so to disable this feature you can call setWantsKeyboardFocus (false).
|
||||
|
||||
The component is also a ChangeBroadcaster, so if you want to be informed when the
|
||||
keyboard is scrolled, you can register a ChangeListener for callbacks.
|
||||
|
||||
@see MidiKeyboardState
|
||||
|
||||
@tags{Audio}
|
||||
*/
|
||||
class JUCE_API MidiKeyboardComponent : public KeyboardComponentBase,
|
||||
private MidiKeyboardState::Listener,
|
||||
private Timer
|
||||
{
|
||||
public:
|
||||
//==============================================================================
|
||||
/** Creates a MidiKeyboardComponent.
|
||||
|
||||
@param state the midi keyboard model that this component will represent
|
||||
@param orientation whether the keyboard is horizontal or vertical
|
||||
*/
|
||||
MidiKeyboardComponent (MidiKeyboardState& state, Orientation orientation);
|
||||
|
||||
/** Destructor. */
|
||||
~MidiKeyboardComponent() override;
|
||||
|
||||
//==============================================================================
|
||||
/** Changes the velocity used in midi note-on messages that are triggered by clicking
|
||||
on the component.
|
||||
|
||||
Values are 0 to 1.0, where 1.0 is the heaviest.
|
||||
|
||||
@see setMidiChannel
|
||||
*/
|
||||
void setVelocity (float velocity, bool useMousePositionForVelocity);
|
||||
|
||||
//==============================================================================
|
||||
/** Changes the midi channel number that will be used for events triggered by clicking
|
||||
on the component.
|
||||
|
||||
The channel must be between 1 and 16 (inclusive). This is the channel that will be
|
||||
passed on to the MidiKeyboardState::noteOn() method when the user clicks the component.
|
||||
|
||||
Although this is the channel used for outgoing events, the component can display
|
||||
incoming events from more than one channel - see setMidiChannelsToDisplay()
|
||||
|
||||
@see setVelocity
|
||||
*/
|
||||
void setMidiChannel (int midiChannelNumber);
|
||||
|
||||
/** Returns the midi channel that the keyboard is using for midi messages.
|
||||
@see setMidiChannel
|
||||
*/
|
||||
int getMidiChannel() const noexcept { return midiChannel; }
|
||||
|
||||
/** Sets a mask to indicate which incoming midi channels should be represented by
|
||||
key movements.
|
||||
|
||||
The mask is a set of bits, where bit 0 = midi channel 1, bit 1 = midi channel 2, etc.
|
||||
|
||||
If the MidiKeyboardState has a key down for any of the channels whose bits are set
|
||||
in this mask, the on-screen keys will also go down.
|
||||
|
||||
By default, this mask is set to 0xffff (all channels displayed).
|
||||
|
||||
@see setMidiChannel
|
||||
*/
|
||||
void setMidiChannelsToDisplay (int midiChannelMask);
|
||||
|
||||
/** Returns the current set of midi channels represented by the component.
|
||||
This is the value that was set with setMidiChannelsToDisplay().
|
||||
*/
|
||||
int getMidiChannelsToDisplay() const noexcept { return midiInChannelMask; }
|
||||
|
||||
//==============================================================================
|
||||
/** Deletes all key-mappings.
|
||||
|
||||
@see setKeyPressForNote
|
||||
*/
|
||||
void clearKeyMappings();
|
||||
|
||||
/** Maps a key-press to a given note.
|
||||
|
||||
@param key the key that should trigger the note
|
||||
@param midiNoteOffsetFromC how many semitones above C the triggered note should
|
||||
be. The actual midi note that gets played will be
|
||||
this value + (12 * the current base octave). To change
|
||||
the base octave, see setKeyPressBaseOctave()
|
||||
*/
|
||||
void setKeyPressForNote (const KeyPress& key, int midiNoteOffsetFromC);
|
||||
|
||||
/** Removes any key-mappings for a given note.
|
||||
|
||||
For a description of what the note number means, see setKeyPressForNote().
|
||||
*/
|
||||
void removeKeyPressForNote (int midiNoteOffsetFromC);
|
||||
|
||||
/** Changes the base note above which key-press-triggered notes are played.
|
||||
|
||||
The set of key-mappings that trigger notes can be moved up and down to cover
|
||||
the entire scale using this method.
|
||||
|
||||
The value passed in is an octave number between 0 and 10 (inclusive), and
|
||||
indicates which C is the base note to which the key-mapped notes are
|
||||
relative.
|
||||
*/
|
||||
void setKeyPressBaseOctave (int newOctaveNumber);
|
||||
|
||||
//==============================================================================
|
||||
/** A set of colour IDs to use to change the colour of various aspects of the keyboard.
|
||||
|
||||
These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
|
||||
methods.
|
||||
|
||||
@see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
|
||||
*/
|
||||
enum ColourIds
|
||||
{
|
||||
whiteNoteColourId = 0x1005000,
|
||||
blackNoteColourId = 0x1005001,
|
||||
keySeparatorLineColourId = 0x1005002,
|
||||
mouseOverKeyOverlayColourId = 0x1005003, /**< This colour will be overlaid on the normal note colour. */
|
||||
keyDownOverlayColourId = 0x1005004, /**< This colour will be overlaid on the normal note colour. */
|
||||
textLabelColourId = 0x1005005,
|
||||
shadowColourId = 0x1005006
|
||||
};
|
||||
|
||||
//==============================================================================
|
||||
/** Use this method to draw a white note of the keyboard in a given rectangle.
|
||||
|
||||
isOver indicates whether the mouse is over the key, isDown indicates whether the key is
|
||||
currently pressed down.
|
||||
|
||||
When doing this, be sure to note the keyboard's orientation.
|
||||
*/
|
||||
virtual void drawWhiteNote (int midiNoteNumber, Graphics& g, Rectangle<float> area,
|
||||
bool isDown, bool isOver, Colour lineColour, Colour textColour);
|
||||
|
||||
/** Use this method to draw a black note of the keyboard in a given rectangle.
|
||||
|
||||
isOver indicates whether the mouse is over the key, isDown indicates whether the key is
|
||||
currently pressed down.
|
||||
|
||||
When doing this, be sure to note the keyboard's orientation.
|
||||
*/
|
||||
virtual void drawBlackNote (int midiNoteNumber, Graphics& g, Rectangle<float> area,
|
||||
bool isDown, bool isOver, Colour noteFillColour);
|
||||
|
||||
/** Callback when the mouse is clicked on a key.
|
||||
|
||||
You could use this to do things like handle right-clicks on keys, etc.
|
||||
|
||||
Return true if you want the click to trigger the note, or false if you
|
||||
want to handle it yourself and not have the note played.
|
||||
|
||||
@see mouseDraggedToKey
|
||||
*/
|
||||
virtual bool mouseDownOnKey (int midiNoteNumber, const MouseEvent& e) { ignoreUnused (midiNoteNumber, e); return true; }
|
||||
|
||||
/** Callback when the mouse is dragged from one key onto another.
|
||||
|
||||
Return true if you want the drag to trigger the new note, or false if you
|
||||
want to handle it yourself and not have the note played.
|
||||
|
||||
@see mouseDownOnKey
|
||||
*/
|
||||
virtual bool mouseDraggedToKey (int midiNoteNumber, const MouseEvent& e) { ignoreUnused (midiNoteNumber, e); return true; }
|
||||
|
||||
/** Callback when the mouse is released from a key.
|
||||
|
||||
@see mouseDownOnKey
|
||||
*/
|
||||
virtual void mouseUpOnKey (int midiNoteNumber, const MouseEvent& e) { ignoreUnused (midiNoteNumber, e); }
|
||||
|
||||
/** Allows text to be drawn on the white notes.
|
||||
|
||||
By default this is used to label the C in each octave, but could be used for other things.
|
||||
|
||||
@see setOctaveForMiddleC
|
||||
*/
|
||||
virtual String getWhiteNoteText (int midiNoteNumber);
|
||||
|
||||
//==============================================================================
|
||||
/** @internal */
|
||||
void mouseMove (const MouseEvent&) override;
|
||||
/** @internal */
|
||||
void mouseDrag (const MouseEvent&) override;
|
||||
/** @internal */
|
||||
void mouseDown (const MouseEvent&) override;
|
||||
/** @internal */
|
||||
void mouseUp (const MouseEvent&) override;
|
||||
/** @internal */
|
||||
void mouseEnter (const MouseEvent&) override;
|
||||
/** @internal */
|
||||
void mouseExit (const MouseEvent&) override;
|
||||
/** @internal */
|
||||
void timerCallback() override;
|
||||
/** @internal */
|
||||
bool keyStateChanged (bool isKeyDown) override;
|
||||
/** @internal */
|
||||
bool keyPressed (const KeyPress&) override;
|
||||
/** @internal */
|
||||
void focusLost (FocusChangeType) override;
|
||||
/** @internal */
|
||||
void colourChanged() override;
|
||||
|
||||
private:
|
||||
//==============================================================================
|
||||
void drawKeyboardBackground (Graphics& g, Rectangle<float> area) override final;
|
||||
void drawWhiteKey (int midiNoteNumber, Graphics& g, Rectangle<float> area) override final;
|
||||
void drawBlackKey (int midiNoteNumber, Graphics& g, Rectangle<float> area) override final;
|
||||
|
||||
void handleNoteOn (MidiKeyboardState*, int, int, float) override;
|
||||
void handleNoteOff (MidiKeyboardState*, int, int, float) override;
|
||||
|
||||
//==============================================================================
|
||||
void resetAnyKeysInUse();
|
||||
void updateNoteUnderMouse (Point<float>, bool isDown, int fingerNum);
|
||||
void updateNoteUnderMouse (const MouseEvent&, bool isDown);
|
||||
void repaintNote (int midiNoteNumber);
|
||||
|
||||
//==============================================================================
|
||||
MidiKeyboardState& state;
|
||||
int midiChannel = 1, midiInChannelMask = 0xffff;
|
||||
int keyMappingOctave = 6;
|
||||
|
||||
float velocity = 1.0f;
|
||||
bool useMousePositionForVelocity = true;
|
||||
|
||||
Array<int> mouseOverNotes, mouseDownNotes;
|
||||
Array<KeyPress> keyPresses;
|
||||
Array<int> keyPressNotes;
|
||||
BigInteger keysPressed, keysCurrentlyDrawnDown;
|
||||
|
||||
std::atomic<bool> noPendingUpdates { true };
|
||||
|
||||
//==============================================================================
|
||||
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiKeyboardComponent)
|
||||
};
|
||||
|
||||
} // namespace juce
|
||||
|
Reference in New Issue
Block a user