JUCE-7.0.12-0-g4f43011b96 JUCE-7.0.12-0-g4f43011b96
JUCE — C++ application framework with suport for VST, VST3, LV2 audio plug-ins

« « « Anklang Documentation
Loading...
Searching...
No Matches
juce_SoundPlayer.cpp
Go to the documentation of this file.
1 /*
2 ==============================================================================
3
4 This file is part of the JUCE library.
5 Copyright (c) 2022 - Raw Material Software Limited
6
7 JUCE is an open source library subject to commercial or open-source
8 licensing.
9
10 By using JUCE, you agree to the terms of both the JUCE 7 End-User License
11 Agreement and JUCE Privacy Policy.
12
13 End User License Agreement: www.juce.com/juce-7-licence
14 Privacy Policy: www.juce.com/juce-privacy-policy
15
16 Or: You may also use this code under the terms of the GPL v3 (see
17 www.gnu.org/licenses).
18
19 JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
20 EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
21 DISCLAIMED.
22
23 ==============================================================================
24*/
25
26namespace juce
27{
28
29// This is an AudioTransportSource which will own it's assigned source
47
48//==============================================================================
49// An AudioSourcePlayer which will remove itself from the AudioDeviceManager's
50// callback list once it finishes playing its source
52 private Timer
53{
55 int samplesPerBlock, double requiredSampleRate)
56 : mixer (mixerToUse), transportSource (ts, ownSource)
57 {
58 jassert (ts != nullptr);
59
60 setSource (transportSource);
61
62 prepareToPlay (samplesPerBlock, requiredSampleRate);
63 start();
64
65 mixer.addInputSource (this, true);
66 startTimerHz (10);
67 }
68
70 {
71 setSource (nullptr);
72 }
73
74 void timerCallback() override
75 {
76 if (! transportSource->isPlaying())
77 mixer.removeInputSource (this);
78 }
79
80private:
81 MixerAudioSource& mixer;
83
85};
86
87// An AudioSource which simply outputs a buffer
89{
90public:
92 : buffer (audioBuffer, ownBuffer),
93 playAcrossAllChannels (playOnAllChannels)
94 {}
95
96 //==============================================================================
98 {
99 jassert (newPosition >= 0);
100
101 if (looping)
102 newPosition = newPosition % static_cast<int64> (buffer->getNumSamples());
103
104 position = jmin (buffer->getNumSamples(), static_cast<int> (newPosition));
105 }
106
107 int64 getNextReadPosition() const override { return static_cast<int64> (position); }
108 int64 getTotalLength() const override { return static_cast<int64> (buffer->getNumSamples()); }
109
110 bool isLooping() const override { return looping; }
111 void setLooping (bool shouldLoop) override { looping = shouldLoop; }
112
113 //==============================================================================
114 void prepareToPlay (int, double) override {}
115 void releaseResources() override {}
116
118 {
119 bufferToFill.clearActiveBufferRegion();
120
121 const int bufferSize = buffer->getNumSamples();
122 const int samplesNeeded = bufferToFill.numSamples;
123 const int samplesToCopy = jmin (bufferSize - position, samplesNeeded);
124
125 if (samplesToCopy > 0)
126 {
127 int maxInChannels = buffer->getNumChannels();
128 int maxOutChannels = bufferToFill.buffer->getNumChannels();
129
130 if (! playAcrossAllChannels)
132
133 for (int i = 0; i < maxOutChannels; ++i)
134 bufferToFill.buffer->copyFrom (i, bufferToFill.startSample, *buffer,
135 i % maxInChannels, position, samplesToCopy);
136 }
137
138 position += samplesNeeded;
139
140 if (looping)
141 position %= bufferSize;
142 }
143
144private:
145 //==============================================================================
147 int position = 0;
148 bool looping = false, playAcrossAllChannels;
149
151};
152
153SoundPlayer::SoundPlayer()
154 : sampleRate (44100.0), bufferSize (512)
155{
156 formatManager.registerBasicFormats();
157 player.setSource (&mixer);
158}
159
161{
162 mixer.removeAllInputs();
163 player.setSource (nullptr);
164}
165
166void SoundPlayer::play (const File& file)
167{
168 if (file.existsAsFile())
169 play (formatManager.createReaderFor (file), true);
170}
171
173{
174 if (resourceData != nullptr && resourceSize > 0)
175 {
176 auto mem = std::make_unique<MemoryInputStream> (resourceData, resourceSize, false);
177 play (formatManager.createReaderFor (std::move (mem)), true);
178 }
179}
180
182{
183 if (reader != nullptr)
184 play (new AudioFormatReaderSource (reader, deleteWhenFinished), true, reader->sampleRate);
185}
186
188{
189 if (buffer != nullptr)
191}
192
194{
195 if (audioSource != nullptr)
196 {
197 AudioTransportSource* transport = dynamic_cast<AudioTransportSource*> (audioSource);
198
199 if (transport == nullptr)
200 {
202 {
204 }
205 else
206 {
207 transport = new AudioTransportSource();
208 transport->setSource (audioSource, 0, nullptr, fileSampleRate);
209 deleteWhenFinished = true;
210 }
211 }
212
213 transport->start();
214 transport->prepareToPlay (bufferSize, sampleRate);
215
216 new AutoRemovingTransportSource (mixer, transport, deleteWhenFinished, bufferSize, sampleRate);
217 }
218 else
219 {
221 delete audioSource;
222 }
223}
224
226{
227 auto soundLength = (int) sampleRate;
228 double frequency = 440.0;
229 float amplitude = 0.5f;
230
231 auto phasePerSample = MathConstants<double>::twoPi / (sampleRate / frequency);
232
233 auto* newSound = new AudioBuffer<float> (1, soundLength);
234
235 for (int i = 0; i < soundLength; ++i)
236 newSound->setSample (0, i, amplitude * (float) std::sin (i * phasePerSample));
237
238 newSound->applyGainRamp (0, 0, soundLength / 10, 0.0f, 1.0f);
239 newSound->applyGainRamp (0, soundLength - soundLength / 4, soundLength / 4, 1.0f, 0.0f);
240
241 play (newSound, true, true);
242}
243
244//==============================================================================
246 int numInputChannels,
247 float* const* outputChannelData,
248 int numOutputChannels,
249 int numSamples,
250 const AudioIODeviceCallbackContext& context)
251{
252 player.audioDeviceIOCallbackWithContext (inputChannelData, numInputChannels,
253 outputChannelData, numOutputChannels,
254 numSamples, context);
255}
256
258{
259 if (device != nullptr)
260 {
261 sampleRate = device->getCurrentSampleRate();
262 bufferSize = device->getCurrentBufferSizeSamples();
263 }
264
265 player.audioDeviceAboutToStart (device);
266}
267
272
273void SoundPlayer::audioDeviceError (const String& errorMessage)
274{
275 player.audioDeviceError (errorMessage);
276}
277
278} // namespace juce
void setNextReadPosition(int64 newPosition) override
Tells the stream to move to a new position.
void releaseResources() override
Allows the source to release anything it no longer needs after playback has stopped.
void setLooping(bool shouldLoop) override
Tells the source whether you'd like it to play in a loop.
void prepareToPlay(int, double) override
Tells the source to prepare for playing.
int64 getNextReadPosition() const override
Returns the position from which the next block will be returned.
void getNextAudioBlock(const AudioSourceChannelInfo &bufferToFill) override
Called repeatedly to fetch subsequent blocks of audio data.
int64 getTotalLength() const override
Returns the total length of the stream (in samples).
bool isLooping() const override
Returns true if this source is actually playing in a loop.
A multi-channel buffer containing floating point audio samples.
AudioFormatReader * createReaderFor(const File &audioFile)
Searches through the known formats to try to create a suitable reader for this file.
A type of AudioSource that will read from an AudioFormatReader.
Reads samples from an audio file stream.
double sampleRate
The sample-rate of the stream.
virtual void audioDeviceError(const String &errorMessage)
This can be overridden to be told if the device generates an error while operating.
Base class for an audio device with synchronised input and output channels.
virtual double getCurrentSampleRate()=0
Returns the sample rate that the device is currently using.
virtual int getCurrentBufferSizeSamples()=0
Returns the buffer size that the device is currently using.
void setSource(AudioSource *newSource)
Changes the current audio source to play from.
void audioDeviceIOCallbackWithContext(const float *const *inputChannelData, int totalNumInputChannels, float *const *outputChannelData, int totalNumOutputChannels, int numSamples, const AudioIODeviceCallbackContext &context) override
Implementation of the AudioIODeviceCallbackWithContext method.
void audioDeviceStopped() override
Implementation of the AudioIODeviceCallback method.
void audioDeviceAboutToStart(AudioIODevice *device) override
Implementation of the AudioIODeviceCallback method.
An AudioSource that takes a PositionableAudioSource and allows it to be played, stopped,...
void prepareToPlay(int samplesPerBlockExpected, double sampleRate) override
Implementation of the AudioSource method.
void setSource(PositionableAudioSource *newSource, int readAheadBufferSize=0, TimeSliceThread *readAheadThread=nullptr, double sourceSampleRateToCorrectFor=0.0, int maxNumChannels=2)
Sets the reader that is being used as the input source.
void start()
Starts playing (if a source has been selected).
Represents a local file or directory.
Definition juce_File.h:45
bool existsAsFile() const
Checks whether the file exists and is a file rather than a directory.
An AudioSource that mixes together the output of a set of other AudioSources.
void removeInputSource(AudioSource *input)
Removes an input source.
void removeAllInputs()
Removes all the input sources.
void addInputSource(AudioSource *newInput, bool deleteWhenRemoved)
Adds an input source to the mixer.
Holds a pointer to an object which can optionally be deleted when this pointer goes out of scope.
A type of AudioSource which can be repositioned.
void audioDeviceAboutToStart(AudioIODevice *) override
Called to indicate that the device is about to start calling back.
void play(const File &file)
Plays a sound from a file.
~SoundPlayer() override
Destructor.
void audioDeviceStopped() override
Called to indicate that the device has stopped.
void audioDeviceError(const String &errorMessage) override
This can be overridden to be told if the device generates an error while operating.
void playTestSound()
Plays a beep through the current audio device.
void audioDeviceIOCallbackWithContext(const float *const *, int, float *const *, int, int, const AudioIODeviceCallbackContext &) override
Processes a block of incoming and outgoing audio data.
The JUCE String class!
Definition juce_String.h:53
Makes repeated callbacks to a virtual method at a specified time interval.
Definition juce_Timer.h:52
void startTimerHz(int timerFrequencyHz) noexcept
Starts the timer with an interval specified in Hertz.
#define jassert(expression)
Platform-independent assertion macro.
#define JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(className)
This is a shorthand way of writing both a JUCE_DECLARE_NON_COPYABLE and JUCE_LEAK_DETECTOR macro for ...
typedef int
JUCE Namespace.
constexpr Type jmin(Type a, Type b)
Returns the smaller of two values.
Type unalignedPointerCast(void *ptr) noexcept
Casts a pointer to another type via void*, which suppresses the cast-align warning which sometimes ar...
Definition juce_Memory.h:88
long long int64
A platform-independent 64-bit integer type.
Additional information that may be passed to the AudioIODeviceCallback.
T sin(T... args)
Used by AudioSource::getNextAudioBlock().
void timerCallback() override
The user-defined callback routine that actually gets called periodically.
Commonly used mathematical constants.