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!
Subscribe:
Youtube
Support:
https://www.buymeacoffee.com/mmshilleh
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
## DONATE AT: https://buymeacoffee.com/mmshilleh
# 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://a.rtmp.youtube.com/live2"
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)
camera.start_preview()
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')
try:
while True:
sleep(60)
except KeyboardInterrupt:
# Stop recording upon receiving a keyboard interrupt (Ctrl+C)
camera.stop_recording()
# Clean up the resources
stream_pipe.stdin.close()
stream_pipe.wait()
camera.close()
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
Conclusion:
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)
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
user@Cam1:/home/pi#
What am I missing here???
You may be on another version of OS, I have a picamera2 version that is compatible with newer OS's
Can you try that?
youtube.com/watch?v=NOAY1aaVPAw