如何使用python录制系统音频

时间:2020-04-15 11:01:19

标签: python audio-recording pyaudio wave

我正在使用python创建录音脚本。在此,我想录制麦克风(外部)和系统(内部)的声音。

要录制外部声音,我使用了pyaudio库。非常适合录制外部声音,并且效果很好。

但是我如何能够记录从计算机发出的系统声音(内部)(例如,在音乐播放器中播放音乐[声音]时)

这是我用来记录麦克风语音的代码。

import tkinter as tk
import threading
import pyaudio
import wave
from tkinter import *

class App():
    chunk = 1024 
    sample_format = pyaudio.paInt16 
    channels = 2
    fs = 44100  

    def __init__(self, master):
        self.isrecording = False
        self.frames = []

        self.button1 = tk.Button(main, text='Record',command=self.startrecording)
        self.button2 = tk.Button(main, text='stop',command=self.stoprecording)
        self.button1.place(x=30, y=30)
        self.button2.place(x=280, y=30)

    def startrecording(self):
        self.p = pyaudio.PyAudio()  
        self.stream = self.p.open(format=self.sample_format,channels=self.channels,rate=self.fs,frames_per_buffer=self.chunk,input=True)
        self.isrecording = True

        print('Recording')
        t = threading.Thread(target=self.record)
        t.start()

    def stoprecording(self):
        self.isrecording = False
        print('recording complete')
        self.filename = 'audio'
        self.filename = self.filename+".wav"
        wf = wave.open(self.filename, 'wb')
        wf.setnchannels(self.channels)
        wf.setsampwidth(self.p.get_sample_size(self.sample_format))
        wf.setframerate(self.fs)
        wf.writeframes(b''.join(self.frames))
        wf.close()
        main.destroy()
    def record(self):
        while self.isrecording:
            data = self.stream.read(self.chunk)
            self.frames.append(data)

main = tk.Tk()
main.title('recorder')
main.geometry('520x120')
app = App(main)
main.mainloop()

0 个答案:

没有答案