spatialaudio / python-sounddevice

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

Blocksize with RawStream #457

Closed toxicrecker closed 1 year ago

toxicrecker commented 1 year ago

I get the following error when I use the blocksize parameter with RawStream

Traceback (most recent call last):
  File "c:\Users\Dhruv\Desktop\cringespeak\client\client.py", line 28, in <module>
    with sd.RawStream(callback=callback, blocksize=4096):
         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Python311\Lib\site-packages\sounddevice.py", line 1384, in __init__    
    _StreamBase.__init__(self, kind='duplex', wrap_callback='buffer',
  File "C:\Python311\Lib\site-packages\sounddevice.py", line 898, in __init__     
    _check(_lib.Pa_OpenStream(self._ptr, iparameters, oparameters,
  File "C:\Python311\Lib\site-packages\sounddevice.py", line 2747, in _check      
    raise PortAudioError(errormsg, err)
sounddevice.PortAudioError: Error opening RawStream: Invalid flag [PaErrorCode -9995]

Code:

import socket
import sounddevice as sd
import time
import queue

sd.default.channels = 2
sd.default.samplerate = 44100
sd.default.latency = 'low'
sd.default.never_drop_input = True

HOST, PORT = "", 8008
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.sendto(b"1", (HOST, PORT))
ack_timeout = int(sock.recv(4096))
sock.sendto(b"2", (HOST, PORT))

output = queue.Queue()
last_ack = time.perf_counter()
def callback(indata, outdata, frames, time, status):
    if status:
        print(status)
    sock.sendto(bytes(indata), (HOST, PORT))
    out = bytes(outdata)
    while not output.empty():
        out += bytes(output.get())
    outdata[:] = bytes(output.get())

with sd.RawStream(callback=callback, blocksize=4096):
    while True:
        data, addr = sock.recvfrom(4096)
        if data == b"2" or (last_ack + ack_timeout) <= time.perf_counter():
            sock.sendto(b"2", (HOST, PORT))
            last_ack = time.perf_counter()
        output.put(data)