spatialaudio / python-sounddevice

:sound: Play and Record Sound with Python :snake:
https://python-sounddevice.readthedocs.io/
MIT License
1.02k stars 149 forks source link

Access violation occurs when playing audio file #462

Closed terryzhao127 closed 1 year ago

terryzhao127 commented 1 year ago

I use the following non-blocking function to play a .wav file on Windows platform.

def playsound(file: Path, device_name: str):
    event = threading.Event()
    data, fs = sf.read(str(file), always_2d=True)

    current_frame = 0

    def callback(out_data, frames, _, __):
        nonlocal current_frame
        chunk_size = min(len(data) - current_frame, frames)
        out_data[:chunk_size] = data[current_frame:current_frame + chunk_size]
        if chunk_size < frames:
            out_data[chunk_size:] = 0
            raise sd.CallbackStop()
        current_frame += chunk_size

    stream = sd.OutputStream(samplerate=fs, device=device_name, channels=data.shape[1], callback=callback,
                             finished_callback=event.set)
    stream.start()
    return event  # Wait until playback is finished

There is a small probability that this error will occur:

Windows fatal exception: access violation

when running:

playsound('xxxx', 'CABLE Input (VB-Audio Virtual Cable), Windows DirectSound').wait()

I have totally no idea which part of my codes is wrong. Could you please help me?

Here is my programming environment:

Python                         3.8.16
sounddevice                    0.4.6
soundfile                      0.12.1

The output device is a virtual device called VB-Audio Virtual Cable.

terryzhao127 commented 1 year ago

Ah, the stream should be stop and close.