I made a program that records files and saves them to a file directory and it does save them properly. However, when I try and open it and see what was recorded I see that it has no stored audio data. I am not sure what I am doing wrong. Please take a look and let me know.
from playsound import playsound
from random import randrange
import pyttsx3
from datetime import datetime
import pyaudio
import speech_recognition as sr
import requests
import wave
import numpy as np
import sounddevice as sd
import math
import time
import os
import sys
import sounddevice as sd
from scipy.io.wavfile import write
import struct
def voiceDetection():
SoundThreshHold = 50
TimeoutLength = 5
chunk = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 2 #Basicly audio output
RATE = 16000 #Rate at which you sample
f_name_directory = r"C:\Users\x\OneDrive\Desktop\Record"
def rms(data):
count = len(data)/2
format = "%dh"%(count)
shorts = struct.unpack( format, data )
sum_squares = 0.0
for sample in shorts:
n = sample * (1.0/32768)
sum_squares += n*n
return math.sqrt( sum_squares / count)*1000
p = pyaudio.PyAudio()
stream = p.open(format=FORMAT,
channels=CHANNELS,
rate=RATE,
input=True,
output=True,
frames_per_buffer=chunk)
currentTime = time.time()
end = time.time() + TimeoutLength
frames = []
while currentTime < end:
currentTime = time.time()
data = stream.read(chunk)
if rms(data) >= SoundThreshHold:
#print(rms(data))
end = time.time() + TimeoutLength
frames.append(data)
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(p.get_sample_size(FORMAT))
wf.setframerate(RATE)
wf.writeframes(data)
wf.close()
print('Written to file: {}'.format(filename))
stream.stop_stream()
stream.close()
p.terminate()
voiceDetection()