如何录制在python脚本中播放的音频?

时间:2019-04-07 15:33:29

标签: python audio recording

我有一个python脚本,可浏览计算机内部的音频文件,并将它们链接到播放声音功能,该功能会在键盘上按下某个键时触发。它工作正常,但是我想要的是能够将按键播放的音频录制到.wav甚至.ogg之类的音频文件中。 我正在使用pygame.mixer加载和播放音频文件。

我在网络上阅读了很多教程,但是这些示例通常是关于从麦克风录制声音的。我的情况是,我需要记录脚本内部产生的声音。

Import pygame
pygame.mixer.init(frequency=44100, size=-16, channels=2, buffer=512)
pygame.init()

# 1
# keypress event 'd'
def key1(event):
    global audio_file_name1
    if audio_file_name1:  # play sound if just not an empty string
        sound1 = pygame.mixer.Sound(audio_file_name1)
        sound1.play()

# Browser button 1
def browse1():
    global audio_file_name1
    audio_file_name1 = filedialog.askopenfilename(filetypes=(("Audio Files", ".wav .ogg"), ("All Files", "*.*")))

# playing button 1
def playsound1():

    global audio_file_name1
    if audio_file_name1:  # play sound if just not an empty string
      sound1 = pygame.mixer.Sound(audio_file_name1)
      sound1.play()

# 2
# keypress event 'a'
def key2(event):
    global audio_file_name2
    if audio_file_name2:  # play sound if just not an empty string
        sound2 = pygame.mixer.Sound(audio_file_name2)
        sound2.play()


# Browser button 2
def browse2():
    global audio_file_name2
    audio_file_name2 = filedialog.askopenfilename(filetypes=(("Audio Files", ".wav .ogg"), ("All Files", "*.*")))


# playing button 2
def playsound2():
    # we will also use the audio_file_name global variable
    global audio_file_name2
    if audio_file_name2:  # play sound if just not an empty string
        sound2 = pygame.mixer.Sound(audio_file_name2)
        sound2.play()

root = Tk()
frame = Frame(root)
audio_file_name1 = ''

# browse button 1
b1 = Button(root, text='open file', bg="yellow", command=browse1)  # browser button 1
b1.pack(anchor=CENTER)

#  playing sound button 1

p1 = Button(root, text='Som1', command=playsound1)  # playsound1
#p1.pack(anchor=W)

# browse button 2
b2 = Button(root, text='open file', bg="light green", command=browse2)  # browser button 2
b2.pack(anchor=CENTER)

#  playing sound button 2

p2 = Button(root, text='Som2', command=playsound2)  # playsound2
#p2.pack(anchor=W)

root.bind('d', key1)
root.bind('a', key2)
root.mainloop()

现在我无法录制自己播放的声音。我希望能够将声音记录在音频文件.wav或.ogg中 谢谢您的帮助!

0 个答案:

没有答案