Python翻录网络在线音乐

来自CloudWiki
跳转至: 导航搜索

安装包

pip3 install sounddevice

pip3 install scipy

代码

import tkinter
from tkinter.messagebox import showinfo
from tkinter.filedialog import asksaveasfilename
from threading import Thread
from numpy import vstack
import sounddevice as sd
from scipy.io import wavfile
#每次录制的秒数
length = 1
for index,device in enumerate(sd.query_devices()):
    if'混音' in device['name']:
        #设置默认录音设备
        sd.default.device[0] = index#设置采样频率
        fs = int(device.get('default_samplerate', 44100))
        break
else:
    showinfo('请注意','没有发现混音设备,录音可能不正常')
    
root = tkinter.Tk()
root.title('录制电脑音频')
root.geometry('300x100+400+300')
root.resizable(False,False)

recording = tkinter.BooleanVar(root,False)

def recorder():
    sounds = []
    lbInfo['text'] ='正在录音...'
    while recording.get():
        #录制声音,每次录制一秒钟,最后再合并
        data = sd.rec(frames=fs*length,samplerate=fs,
                      blocking=True, channels=2)
        sounds.append(data)
    sounds = vstack(sounds)
    filename = asksaveasfilename(title='保存声音',
                                 filetypes=[('wavfile','*.wav')])
    if not filename:
        return
    if not filename.endswith( '.wav ' ):
        filename = filename + '.wav'
    lbInfo[ 'text' ] ='正在保存文件...'
    #把录制的声音保存为wav文件
    wavfile.write(filename,fs, sounds)
    lbInfo[ 'text'] ='保存完成.'

def start_recording():
    global thread_recorder
    recording.set(True)
    #创建并启动线程
    thread_recorder = Thread(target=recorder)
    thread_recorder.start()
    buttonStop['state'] = 'normal'
    buttonStart['state'] ='disabled'
buttonStart = tkinter.Button(root,text='开始录音',
                             command=start_recording)
buttonStart.place(x=10,y=10,width=130,height=20)

def stop_recording():
    recording.set(False)
    buttonStop['state'] = 'disabled'
    buttonStart['state'] = 'normal'
buttonStop = tkinter.Button(root,text='停止录音', state='disabled',
                            command=stop_recording)
buttonStop.place(x=160,y=10,width=130,height=20)
        
lbInfo = tkinter.Label(root,foreground='red')
lbInfo.place(x=10,y=40,width=280,height=20)

root.mainloop()

参考文档:https://mp.weixin.qq.com/s?__biz=MzI4MzM2MDgyMQ==&mid=2247492756&idx=1&sn=5b4f8a2234c800531e9d91de0cfe9a19&chksm=eb894fcedcfec6d807df933b7a08fafb34616a07507ff085f73188f916ad8233bab08589e55f&mpshare=1&scene=23&srcid=0127nSliquhipBqv6QqUAz7v&sharer_sharetime=1611704620720&sharer_shareid=9a47d948e5a338ea483d560dfedff359#rd