我试图在 Python 中同时运行两种方法。其中一个播放声音,另一个录制声音。两种方法都可以正常工作,但我无法弄清楚如何在尝试多处理和线程的同时启动它们。而我现在几乎可以肯定它不能用线程来解决。
def listen_to_audio()
def play_audio()
有任何想法吗?(它们不必同时完成,但它们都应该在一秒钟内开始。)
那是代码,很抱歉没有在开头发布它:
import pyaudio
import wave
import sys
import time
from math import *
from getopt import *
import threading
def make_sin(f0=1000.,ampl=30000,rate=22050,length=5.):
a = 2. * pi * f0/rate
n = int(rate * length)
wav=''
for i in range(0, n):
f = int(ampl*sin(a*i))
wav += chr(f & 0xFF) + chr((f & 0xFF00) >> 8)
return wav
def play_audio(forHowLong):
data = make_sin(f0=1000.,ampl=30000,rate=22050,length=5.)
p = pyaudio.PyAudio() #sets up portaudio system
stream = p.open(format=p.get_format_from_width(2),
channels=1,
rate=22050,
output=True)
start = time.time()
while time.time() < start + forHowLong*0.5:
stream.write(data)
stream.stop_stream()
stream.close()
p.terminate()
def listen_to_audio(forHowLong):
CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 2
RATE = 44100
RECORD_SECONDS = forHowLong
WAVE_OUTPUT_FILENAME = "output.wav"
p = pyaudio.PyAudio()
stream = p.open(format=FORMAT,
channels=CHANNELS,
rate=RATE,
input=True,
frames_per_buffer=CHUNK)
print("* recording")
frames = []
for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
data = stream.read(CHUNK)
frames.append(data)
print("* done recording")
stream.stop_stream()
stream.close()
p.terminate()
wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
wf.setnchannels(CHANNELS)
wf.setsampwidth(p.get_sample_size(FORMAT))
wf.setframerate(RATE)
wf.writeframes(b''.join(frames))
wf.close()
def main():
#start play_audio and record_audio here at the same time
if __name__ == "__main__":
main()