python-sounddevice
python-sounddevice copied to clipboard
Can't write to a callback stream [PaErrorCode -9976]
I'm trying to get the current audio level of the wav file thats playing using a callback function. When ran it results in, sounddevice.PortAudioError: Can't write to a callback stream [PaErrorCode -9976]
The audio plays correctly when the callback parameter is removed.
Here's the code...
import soundfile as sf
import sounddevice as sd
import numpy as np
path_to_audio = "add audio path here"
def print_audio_level(outdata, frames, time, status):
# Calculate the audio level as the RMS of the audio data
audio_level = 20 * np.log10(np.sqrt(np.mean(np.square(outdata))))
# Print the current audio level
print("Current audio level:", audio_level, "dB")
# Read the audio file using soundfile
audio, sample_rate = sf.read(path_to_audio)
audio = audio.astype(np.float32)
# Set up the audio playback stream
playback_stream = sd.OutputStream(samplerate=sample_rate, channels=1, callback=print_audio_level)
# Start the audio playback stream
playback_stream.start()
# Play the audio file
playback_stream.write(audio)
# Stop the audio stream (wait for playback to finish)
playback_stream.stop()
# Close the audio stream
playback_stream.close()
The error message says it all.
But maybe it's not clear what a "callback stream" is?
A callback stream is a stream with a callback function.
Your stream has a callback function, and you are trying to write to it.
But you can't.
The audio plays correctly when the callback parameter is removed.
Exactly, because then it ceases to be a callback stream and you can write to it.