How can I add audio to video?
Overview
Sorry for this simple question, but I couldn't figure it out.
I want to load a video, process each frame, and then write it with changes. for loading video I use open-cv, but for writing I use PyAV
I took a code from this awesome guy at Stack Overflow and the video writer works flawlessly, but I want to add audio to it.
this is my code:
width, height, fps = width, height, fps # Select video resolution and framerate.
output_memory_file = io.BytesIO() # Create BytesIO "in memory file".
output = av.open(output_memory_file, 'w', format="mp4") # Open "in memory file" as MP4 video output
stream = output.add_stream('h264', str(fps)) # Add H.264 video stream to the MP4 container, with framerate = fps.
stream.width = width # Set frame width
stream.height = height # Set frame height
stream.pix_fmt = 'yuv444p' # Select yuv444p pixel format (better quality than default yuv420p).
stream.options = {'crf': '17'} # Select low crf for high quality (the price is larger file size).
# Done breaking down video to pictures and making them pixeled, now making it videos back.
# imgs is a dict with numbered frames as PIL Image
for i in range(len(imgs)):
frame = av.VideoFrame.from_image(imgs[i])
packet = stream.encode(frame) # Encode video frame
output.mux(packet) # "Mux" the encoded frame (add the encoded frame to MP4 file).
# Flush the encoder
packet = stream.encode(None)
output.mux(packet)
output.close()
# Write BytesIO from RAM to file, for testing
with open(video_name, "wb") as f:
f.write(output_memory_file.getbuffer())
can anyone help me?