PythonのSocketを利用して音楽を流しながら自分の声を送信したい
PyAudio,socketを利用して、自分の声と同時に音楽を流したいと思ったのですが、threadを利用して同時に行おうとすると以下のエラーが出てしまい、自分の声が届かなくなってしまいます。
発生している問題・エラーメッセージ
Exception in thread Thread-2: Traceback (most recent call last): File "C:\Users\x\AppData\Local\Programs\Python\Python37-32\lib\threading.py", line 926, in _bootstrap_inner self.run() File "C:\Users\x\AppData\Local\Programs\Python\Python37-32\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "server.py", line 58, in acceptSounds stream.write(data) File "C:\Users\x\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pyaudio.py", line 586, in write exception_on_underflow) OSError: [Errno -9988] Stream closed
該当のソースコード
python
1import pyaudio 2import socket 3import wave 4import threading 5 6FORMAT = pyaudio.paInt16 7CHANNELS = 1 8RATE = 44100 9CHUNK = 4096 10 11host = socket.gethostname() 12port = 9999 13 14s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 15s.bind((host, port)) 16s.listen(1) 17 18audio = pyaudio.PyAudio() 19 20stream = audio.open(format=FORMAT, 21 channels=CHANNELS, 22 rate=RATE, 23 output=True, 24 frames_per_buffer=CHUNK) 25 26def playMusic(): 27 while True: 28 try: 29 wf = wave.open('./carengine.wav', 'rb') 30 31 p = pyaudio.PyAudio() 32 33 music_stream = p.open(format = p.get_format_from_width(wf.getsampwidth()), 34 channels = wf.getnchannels(), 35 rate = wf.getframerate(), 36 output = True) 37 38 musicData = wf.readframes(CHUNK) 39 40 while len(musicData) > 0: 41 music_stream.write(musicData) 42 musicData = wf.readframes(CHUNK) 43 44 music_stream.stop_stream() 45 music_stream.close() 46 audio.terminate() 47 except KeyboardInterrupt: 48 break 49 50def acceptSounds(): 51 while True: 52 try: 53 print('waiting for connection') 54 connection, address = s.accept() 55 with connection: 56 while True: 57 data = connection.recv(CHUNK) 58 stream.write(data) 59 if not data: 60 break 61 except KeyboardInterrupt: 62 break 63 64 print('shutting down') 65 s.close() 66 stream.close() 67 audio.terminate() 68 69if __name__ == '__main__': 70 music_thread = threading.Thread(target = playMusic) 71 accept_thread = threading.Thread(target = acceptSounds) 72 73 music_thread.start() 74 accept_thread.start() 75 76 music_thread.join() 77 accept_thread.join()
import pyaudio import socket FORMAT = pyaudio.paInt16 CHANNELS = 1 RATE = 44100 CHUNK = 4096 audio = pyaudio.PyAudio() host = socket.gethostname() port = 9999 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((host, port)) stream = audio.open(format=FORMAT, channels=CHANNELS, rate=RATE, input=True, frames_per_buffer=CHUNK) print("recording") try: while True: data = stream.read(CHUNK) s.send(data) except KeyboardInterrupt: pass print("finished recording") s.close() stream.stop_stream() stream.close() audio.terminate()
試したこと
CHUNKの値を変えたり、ThreadPoolExecutorを使ってみたりしました。
補足情報(FW/ツールのバージョンなど)
Python3.7.4
回答1件
あなたの回答
tips
プレビュー