Nov-30-2020, 12:35 PM
(This post was last modified: Nov-30-2020, 12:35 PM by Talking2442.)
Hello Guys,
I want play a variable with pyAudio like with:
But I cant get them working...
Anyone can help me?
I want play a variable with pyAudio like with:
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'C:\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):
print('Playing...')
while len(recording) > 0:
self.stream.read(recording)
self.stream.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()
a = Recorder()
a.listen()The original script cames from Stack Overflow and I want playing the variable without writing it to file (protect HDD healthy).But I cant get them working...
Anyone can help me?

