Sitemap / Advertise

Information



Tags



Share

How to convert h264 to mp4 with MP4Box on Raspberry Pi in Python

Advertisement:


read_later

Read Later

Keywords



Keywords



read_later

Read Later

Information

Tags

Share





Advertisement

Advertisement


Banggood
Banggood


Definition

Raspberry Pi records videos in the h264 format by default, but unfortunately, the h264 format is not supported by most of the applications which you can use in collaboration with your Raspberry Pi, for instance, WhatsApp. And thus, in this tutorial, I will show you how to convert a recently recorded video in the h264 format to the mp4 format automatically in Python.

To convert video formats, I used MP4Box: you can download it to your Raspberry Pi, as shown here:

The Pi captures video as a raw H264 video stream. Many media players will refuse to play it, or play it at an incorrect speed, unless it is "wrapped" in a suitable container format like MP4. The easiest way to obtain an MP4 file from the raspivid command is using MP4Box(1).

sudo apt install -y gpac

Code

Import the required modules.

Initiate the camera module with pre-defined settings.

Define the convert function:

Record a 15 seconds video with the given filename (h264).

Convert the h264 format to the mp4 format by activating the terminal with the MP4Box command.

Set filenames and call the convert function.

Note: If you want, you can use the same method to convert existing videos without recording.


------------ Python ------------

from picamera import PiCamera
from time import sleep
from subprocess import call 

# Initiate the camera module with pre-defined settings.
camera = PiCamera()
camera.resolution = (640, 480)
camera.framerate = 15

def convert(file_h264, file_mp4):
    # Record a 15 seconds video.
    camera.start_recording(file_h264)
    sleep(15)
    camera.stop_recording()
    print("Rasp_Pi => Video Recorded! \r\n")
    # Convert the h264 format to the mp4 format.
    command = "MP4Box -add " + file_h264 + " " + file_mp4
    call([command], shell=True)
    print("\r\nRasp_Pi => Video Converted! \r\n")
    

# Record a video and convert it (MP4).
convert('/home/pi/test.h264', '/home/pi/test.mp4')

Result:

You can inspect my electronics project in which I used the mentioned method to convert h264 videos to mp4 videos from here.

References

(1) https://www.raspberrypi.org/documentation/usage/camera/raspicam/raspivid.md