How to stop AudioSource.getNextAudioBlock() from being called

In my app, I’m using an AudioSource to output audio samples:

AudioSamplePlayer::AudioSamplePlayer()
{
	player = std::make_unique<juce::AudioSourcePlayer>();
	player->setSource(this);
	deviceManager.addAudioCallback(player.get());
}

void AudioSamplePlayer::start()
{
	deviceManager.initialiseWithDefaultDevices(0, 2);
}

void AudioSamplePlayer::prepareToPlay(int samplesPerBlock, double sampleRate) {}

void AudioSamplePlayer::releaseResources() {}

void AudioSamplePlayer::getNextAudioBlock(const juce::AudioSourceChannelInfo& bufferToFill)
{
	for (auto channel = 0; channel < bufferToFill.buffer->getNumChannels(); ++channel)
	{
		auto* buffer = bufferToFill.buffer->getWritePointer (channel, bufferToFill.startSample);
		for (auto a = 0 ; a < bufferToFill.numSamples ; a++)
		{
			buffer[a] = (((float) rand() / RAND_MAX) - 0.5) / 2;
		}
	}
}

When I want to start playing, so the getNextAudioBlock() is called, I call the start() function.

Now I want to know how to stop getNextAudioBlock() to be called.
How can I do that?

Thanks.

From our discord communication:

You can turn on and off the AudioIODevice from the AudioDeviceManager:

deviceManager.closeAudioDevice();
// and on:
deviceManager.restartLastAudioDevice();

Alternatively you can plug an AudioTransportSource between this and the player:

AudioSamplePlayer::AudioSamplePlayer()
{
	player = std::make_unique<juce::AudioSourcePlayer>(); // N.B. this doesn't need to be a pointer
        transportSource.setSource (this);
	player->setSource (&transportSource);
	deviceManager.addAudioCallback (player.get());
}
1 Like

OK sor, for the moment, I just chose to add a function in my class:

void AudioSamplePlayer::stop()
{
    deviceManager.closeAudioDevice();
}

And it works like a charm.

Thanks!