0

i bought an USB microphone and a Camera module for the raspberry pi4. I managed to record Audio and Video but when i merge them with ffmpeg the are not synchronized, i'm trying to solve this for 2 days now.

Here my code, when the program starts it record video with the instruction "camera.start_recording("Video.h264")", this instruction return immediatly so when the program executes the instruction after camera.start_recording("Video.h264") the video is still recording.

For recording Audio i use a while loop that stops when i press a button. When i press the button the video recording also stops.

After everything is written i use ffmpeg to merge the video (After converting it to mp4) and the Audio.

# coding=utf-8

from picamera import PiCamera
import pyaudio
import wave
import os
import time
import RPi.GPIO as GPIO

GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(10, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
print("Ready")
go = True

camera = PiCamera()
camera.resolution = (1920, 1080)

audio = pyaudio.PyAudio()
stream = audio.open(format=pyaudio.paInt16, channels=1, rate=44100, input=True)

frames = []
camera.start_recording("Video.h264")

while go:
    print("Recording")
    if GPIO.input(10) == GPIO.HIGH:
        camera.stop_recording()
        go = False

    print("Recording has been stopped")
    data = stream.read(1024, exception_on_overflow = False)
    frames.append(data)

stream.stop_stream()
stream.close()
audio.terminate()

sound_file = wave.open("Audio.wav", "wb")
sound_file.setnchannels(1)
sound_file.setsampwidth(audio.get_sample_size(pyaudio.paInt16))
sound_file.setframerate(44100)
sound_file.writeframes(b''.join(frames))
sound_file.close()

print("Converting in mp4")
os.system("ffmpeg -i Video.h264 Video.mp4")

print("Merging audio and video")
os.system("ffmpeg -i Video.mp4 -i Audio.wav -c:v copy -c:a aac vea.mp4")

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.