hab mal wieder ein neues Problem unzwar wenn ich diesen Code ausführe:
Code: Alles auswählen
from io import BytesIO
import pyaudio
import math
import struct
import wave
import time
import os
Threshold = 10
SHORT_NORMALIZE = (1.0 / 32768.0)
chunk = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 16000
swidth = 2
TIMEOUT_LENGTH = 5
f_name_directory = r'./records'
class Recorder:
@staticmethod
def rms(frame):
count = len(frame) / swidth
format = "%dh" % (count)
shorts = struct.unpack(format, frame)
sum_squares = 0.0
for sample in shorts:
n = sample * SHORT_NORMALIZE
sum_squares += n * n
rms = math.pow(sum_squares / count, 0.5)
return rms * 1000
def __init__(self):
self.p = pyaudio.PyAudio()
self.stream = self.p.open(format=FORMAT,
channels=CHANNELS,
rate=RATE,
input=True,
output=True,
frames_per_buffer=chunk)
def record(self):
print('Noise detected, recording beginning')
rec = []
current = time.time()
end = time.time() + TIMEOUT_LENGTH
while current <= end:
data = self.stream.read(chunk)
if self.rms(data) >= Threshold: end = time.time() + TIMEOUT_LENGTH
current = time.time()
rec.append(data)
# self.write(b''.join(rec))
self._play(b''.join(rec))
def write(self, recording):
n_files = len(os.listdir(f_name_directory))
filename = os.path.join(f_name_directory, '{}.wav'.format(n_files))
wf = wave.open(filename, 'wb')
wf.setnchannels(CHANNELS)
wf.setsampwidth(self.p.get_sample_size(FORMAT))
wf.setframerate(RATE)
wf.writeframes(recording)
wf.close()
print('Written to file: {}'.format(filename))
print('Returning to listening')
def _play(self, recording):
# open the file for reading.
wf = wave.open(BytesIO(recording), 'rb')
wf.setnchannels(CHANNELS)
wf.setsampwidth(self.p.get_sample_size(FORMAT))
wf.setframerate(RATE)
# read data (based on the chunk size)
data = wf.readframes(chunk)
# play stream (looping from beginning of file to the end)
print('Play listened')
while data != '':
# writing to the stream is what *actually* plays the sound.
self.p.write(data)
data = wf.readframes(chunk)
# cleanup stuff.
self.p.close()
self.p.terminate()
def listen(self):
print('Listening beginning')
while True:
input = self.stream.read(chunk)
rms_val = self.rms(input)
if rms_val > Threshold:
self.record()
x = Recorder()
x.listen()
Code: Alles auswählen
File "./test2.py", line 112, in <module>
x.listen()
File "./test2.py", line 107, in listen
self.record()
File "./test2.py", line 64, in record
self._play(b''.join(rec))
File "./test2.py", line 82, in _play
wf = wave.open(BytesIO(recording), 'rb')
File "/usr/lib/python3.7/wave.py", line 510, in open
return Wave_read(f)
File "/usr/lib/python3.7/wave.py", line 164, in __init__
self.initfp(f)
File "/usr/lib/python3.7/wave.py", line 131, in initfp
raise Error('file does not start with RIFF id')
wave.Error: file does not start with RIFF id
Bin für jede Hilfe dankbar.
MfG
MpOnE