多个线程无法正常工作

时间:2017-08-08 13:05:51

标签: python multithreading audio-recording

我想创建两个线程,所以当我运行程序时,第一个线程激活函数" recorder"录制音频,5秒后停止播放,第二个线程激活以进行某些活动。 n秒后,thread2停止,thread1回到原位。这个过程一直持续到我们使用键盘异常终止它。

我有以下代码。它从录制音频开始,保存它,但第二个线程似乎没有工作,因为程序完成退出代码0。 有人能纠正我在哪里弄错了吗?感谢

from threading import  Thread
import time
from time import ctime
import pyaudio
import wave

def recorder(name, delay, repeat):
    FORMAT = pyaudio.paInt16
    CHANNELS = 2
    RATE = 44100
    CHUNK = 1024
    RECORD_SECONDS = 3
    WAVE_OUTPUT_FILENAME = "file.wav"

    audio = pyaudio.PyAudio()

    # start Recording
    stream = audio.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("finished recording")

    # stop Recording
    stream.stop_stream()
    stream.close()
    audio.terminate()

    waveFile = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
    waveFile.setnchannels(CHANNELS)
    waveFile.setsampwidth(audio.get_sample_size(FORMAT))
    waveFile.setframerate(RATE)
    waveFile.writeframes(b''.join(frames))
    waveFile.close()

def save(name, delay, repeat):
    print("Saved")

def Main():
    t1 = Thread(target=recorder, args=("Timer1", 1, 5))
    t2 = Thread(target=save, args=("Timer2", 5, 5))
    t1.start()
    t2.start()

    print("Main complete")

if __name__ == '__main__':
    Main()

0 个答案:

没有答案