DEV Community

Cover image for Stream Video from Raspberry Pi Camera to YouTube Live

Posted on

Stream Video from Raspberry Pi Camera to YouTube Live

Learn how to easily stream video from your Raspberry Pi to YouTube live in Python in a few simple steps. By the end of this video, you will be able to have a publicly viewable live stream with a simple hardware setup.
Before reading the remainder, be sure to subscribe and support the channel if you have not!



Step 1-) Library Setup

Run the following commands in a terminal on Raspberry Pi
sudo apt install python3-picamera ffmpeg

Step 2-) Code Setup

Now that you have the libraries you can go ahead and create a Python file and substitute this code.

import subprocess
from picamera import PiCamera
from time import sleep

## Author: Mahmood Mustafa Youssef Shilleh

# Set up camera constants
RESOLUTION = (640, 480)  # Can be adjusted based on your needs
FRAMERATE = 24           # Adjust this based on your camera's capabilities

# YouTube Stream URL and Key
YOUTUBE_URL = "rtmp://"
YOUTUBE_KEY = "<key>"  # Replace with your actual YouTube stream key

# Construct the FFmpeg command for streaming
stream_cmd = f'ffmpeg -ar 44100 -ac 2 -acodec pcm_s16le -f s16le -ac 2 -i /dev/zero -f h264 -i - -vcodec copy -acodec aac -ab 128k -g 50 -strict experimental -f flv {YOUTUBE_URL}/{YOUTUBE_KEY}'

# Initialize the camera
camera = PiCamera(resolution=RESOLUTION, framerate=FRAMERATE)
sleep(2)  # Camera warm-up time

# Start the streaming subprocess
stream_pipe = subprocess.Popen(stream_cmd, shell=True, stdin=subprocess.PIPE)

# Start recording and streaming
camera.start_recording(stream_pipe.stdin, format='h264')

    while True:
except KeyboardInterrupt:
    # Stop recording upon receiving a keyboard interrupt (Ctrl+C)

# Clean up the resources
The only thing you need to do is substitute your streaming key, which you can get from YouTube when you start a live stream.
Screenshot 2024-04-20 at 10.12.56 PM.png
Enter fullscreen mode Exit fullscreen mode


That should be all you need to stream to YouTube live! Hope you got it working. If you did, please subscribe to the channel or consider donating at the buymeacoffee link above. Thanks.

Top comments (2)

owlisen profile image

I don't know if it's me who is stupid or what...

I've tried to run "sudo apt install python3-picamera ffmpeg"
I get this...

Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
Package python3-picamera is not available, but is referred to by another package.
This may mean that the package is missing, has been obsoleted, or
is only available from another source

E: Package 'python3-picamera' has no installation candidate

What am I missing here???

shilleh profile image

You may be on another version of OS, I have a picamera2 version that is compatible with newer OS's

Can you try that?