简体   繁体   中英

Add multiple Layers to audio recording with PyAudio

Im been experimenting with audio recording and playback using pyaudio .

I'm able to record a file but I need to be able to add layers on top of it. What I'm trying to do is record a 10 second file then start playing.

While its playing I want to continue to record additional 10 sec layers and add them over top of the prior recording.

Is there a way to do this with 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()

I found a module called "PyDub" which does this easily.

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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM