speech-scoring/record_mic_speech.py

56 lines
1.3 KiB
Python

import pyaudio
import numpy as np
from matplotlib import pyplot as plt
CHUNKSIZE = 44100 * 10 # fixed chunk size
# initialize portaudio
p_inp = pyaudio.PyAudio()
# dev_n = p.get_device_count()
# dev_infos = [p.get_device_info_by_index(index) for index in range(dev_n)]
# [i for i in dev_infos] # if i['name'] == 'record']
stream = p_inp.open(
format=pyaudio.paInt24,
channels=2,
rate=44100,
input=True,
frames_per_buffer=CHUNKSIZE)
# do this as long as you want fresh samples
data = stream.read(CHUNKSIZE)
len(data)
CHUNKSIZE*10
numpydata = np.fromstring(data, dtype=np.int16)
# plot data
plt.plot(numpydata)
plt.show()
# close stream
stream.stop_stream()
stream.close()
p_inp.terminate()
# open the file for reading.
# wf = wave.open(sys.argv[1], 'rb')
# create an audio object
# p = pyaudio.PyAudio()
# open stream based on the wave object which has been input.
p_oup = pyaudio.PyAudio()
stream = p_oup.open(
format=pyaudio.paInt24, channels=2, rate=44100, output=True)
# read data (based on the chunk size)
# data = wf.readframes(CHUNKSIZE)
# play stream (looping from beginning of file to the end)
# while data != '':
# writing to the stream is what *actually* plays the sound.
stream.write(data)
# data = wf.readframes(chunk)
# cleanup stuff.
stream.close()
p_oup.terminate()