一 概念基础

这次用python实现一个定时录音机的功能,可以让你的i电脑秒变定时录音机。

这里用到了wave库,time库等。熟悉该源码,即可了解这些库的用法。

 

二 源码解析

1.录音函数,该函数使用了wave和pyaudio两个库来完成录音和文件存储。

def rec_start():

    chunk = 1024  # Record in chunks of 1024 samples
    sample_format = pyaudio.paInt16  # 16 bits per sample
    channels = 1
    fs = 44100  # Record at 44100 samples per second
    seconds = 300
    current_time = time.strftime("%m.%d.%y %H:%M", time.localtime())
    #filename = "output.wav"
    current_time = time.strftime("%m_%d_%y_%H_%M", time.localtime())
    file_name = 'rec_%s.wav' % current_time

    p = pyaudio.PyAudio()  # Create an interface to PortAudio

    print('Recording file name:',file_name)

    stream = p.open(format=sample_format,
                channels=channels,
                rate=fs,
                frames_per_buffer=chunk,
                input=True)

    frames = []  # Initialize array to store frames

    # Store data in chunks for 3 seconds
    for i in range(0, int(fs / chunk * seconds)):
        data = stream.read(chunk)
        frames.append(data)

    # Stop and close the stream
    stream.stop_stream()
    stream.close()
    # Terminate the PortAudio interface
    p.terminate()
    print('Finished recording')

    # Save the recorded data as a WAV file
    wf = wave.open(file_name, 'wb')
    wf.setnchannels(channels)
    wf.setsampwidth(p.get_sample_size(sample_format))
    wf.setframerate(fs)
    wf.writeframes(b''.join(frames))
    wf.close()
    print('Finished save file')

2. 定时函数,该函数用timer实现了特地时间的动作触发。

def func():
    print("start rec audio")
    rec_start()
    timer = threading.Timer(86400,func)
    timer.start()


now_time = datetime.datetime.now()

next_time = now_time + datetime.timedelta(days=+1)
next_year = next_time.date().year
next_month = next_time.date().month
next_day = next_time.date().day

#get next day 3:00 time
next_time = datetime.datetime.strptime(str(next_year)+"-"+str(next_month)+"-"+str(next_day)+" 03:00:00", "%Y-%m-%d %H:%M:%S")

timer_start_time = (next_time - now_time).total_seconds()
print(timer_start_time)

timer = threading.Timer(timer_start_time,func)
timer.start()


三 总结

上面没全贴出来源码,剩下的就是库函数的import了,留个课后作业吧。

  作者:虚生