使用PyAudio

时间:2017-12-01 02:47:31

标签: python audio recording pyaudio

我正在尝试使用pyaudio进行录音和播放。

我能够录制文件,但我需要能够在其上添加图层。我想要做的就是录制一个10秒的文件然后开始播放。

在播放时,我想继续录制额外的10秒图层并将其添加到之前录制的顶部。

有没有办法用Python做到这一点?

import pyaudio
import wave

CHUNK = 2
FORMAT = pyaudio.paInt16
CHANNELS = 2
RATE = 44100
RECORD_SECONDS = 3
WAVE_OUTPUT_FILENAME = "output.wav"

p = pyaudio.PyAudio()

stream = p.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(int(RATE / CHUNK * RECORD_SECONDS))

print("* done recording")

stream.stop_stream()
stream.close()
p.terminate()

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

1 个答案:

答案 0 :(得分:0)

我找到了一个名为" PyDub"这很容易做到。

http://pydub.com/

from pydub import AudioSegment

track1 = AudioSegment.from_file(track1wav)
track2 = AudioSegment.from_file(track2wav)

combined = track1.overlay(track2)
print ("overlaying recording")
combined.export(track1wav, format='wav')