How To Stream Video From Raspberry Pi To Your Phone?

Since its advent, raspberry pi has seen uses in a huge variety of applications.

Its applications range from using raspberry pi to build a simple hobby project like turning LEDs on and off, creating an automated system, using it as a secondary PC to making your own cell phone.

I have shared many Raspberry Pi applications here on Yantraas in the past and today I am sharing one of my personal favorites.

Today let’s learn how to interface a camera with a raspberry pi and stream video from raspberry pi to phone.

Many will consider that this is an advanced raspberry pi project, well to a certain degree that’s true.

But here is the thing with raspberry pi, being what it is, being a hardware unit that invites such a huge domain of applications, if you are willing you will get most of your doubts resolved.

And on top of that, I have created almost all the articles that you will need to clear your basics here on Yantraas, in order to attempt this project on streaming video from raspberry pi to your phone.

I will enlist them below. So, without any further ado, let’s get into it by first answering the most important question,

Can you actually stream video using a raspberry pi?

Yes, with the advanced technology and hardware that is created around raspberry pi, you can easily set up your raspberry pi to stream live (or otherwise) video and access the stream using your phone, PC, or any device of your choice.

With that little query out of the way, let’s go ahead and see how exactly you can stream video from raspberry pi to your phone.

stream video from raspberry pi to phone

Setting Everything Up

To be honest with there are actually quite a few ways to accomplish live video streaming on your Raspberry Pi.

I am going to teach you how to stream video from raspberry pi to your phone using raspberry pi camera module V2 and the server script provided by the official PiCamera package documentation.

There are some complicated ways to accomplish the same thing but this method of video streaming should feel easy even to beginners.

So, first things first, here is everything that you are going to need.

  • Raspberry Pi
  • Raspberry Pi Camera Module V2
  • Keyboard and Mouse
  • Micro HDMI to HDMI cable
  • A monitor
  • Ethernet cable (If you want a wired connection else no need)
  • microSD card
  • A Raspberry Pi Case (optional)

Once you have all of these hardware units. You need to properly set up your raspberry pi so that we can work with it.

I have created an elaborate post on how to set up a raspberry pi properly here.

If you are a beginner, I highly recommend you go through the guide to set up your Raspberry Pi. This is because I have shared many important tips that you as a beginner should not miss at any cost.

For intermediates and advanced raspberry pi users these two articles will be useful,

Once you have completed the above steps, the next thing you need to do is connect all the units together.

  • Connect USB mouse and keyboard to the available USB slots.
  • Next, connect the monitor using the micro HDMI to HDMI cable.
  • Now carefully, connect the camera module V2 using the ribbon connector on the raspberry pi.
  • Finally, connect the power supply and switch everything on to enter into the Raspbian OS.

Initializing Camera

Okay, if you have successfully booted the raspberry pi to the Raspbian desktop, you have won half the fight.

The next thing that we are going to do is do some settings in the Raspbian desktop environment, in order to receive the stream.

Before you can use the camera module with your raspberry pi, you need to enable the camera software in order to be able to use it.

To do that, in the desktop environment, in the preferences menu, go to the Raspberry Pi Configuration window, open the Interfaces tab, click on the Enabled option button and click on ok as shown.

enabling camera module in raspberry pi
Enabling Camera Module

This will open up the camera port and will make image/video file transmission possible.

You can achieve the same thing using the Terminal as well.

Just type the following command,

pi@raspberry:~ $ sudo raspi-config

This will open up the Raspberry Pi Software Configuration Tool.

In the interfacing options, enable the camera and reboot your raspberry pi.

Select Interfacing Options
Enable Camera

Final Preparatory Steps Before Streaming To Your Phone

Alright, so it’s time to get our project up and running by writing the relevant code for the same.

But before we do that there are a few preliminary steps that we will have to take.

  • First, make sure you have connected the camera properly.

Connecting the camera module V2 should be easy enough and I am hoping you have already done it.

But here is a quick rundown on how to do it. Making sure that the Pi is OFF, connect the camera to the CSI port of Pi with the help of the provided ribbon connector.

What you need to keep in mind is the orientation of the connection. One way to ensure that you are connecting the ribbon connector correctly is by making the side of the ribbon connector with the letterings and markings face up.

The arrangement should look like this.

stream video from raspberry pi to phone using camera module V2
Raspberry Pi Connected With Camera Module V2
  • Secondly, find out the IP address of your Raspberry Pi

This is very important because we will be needing this IP address to be able to stream the live feed to our phone and to access our video streaming server.

Find the IP address of your Raspberry Pi is fairly easy.

Just open your terminal and type the following command.

pi@raspberry:~ $ ifconfig

As soon as you enter the command on the terminal you should see a myriad of information in front of you.

The one piece of information that is going to be important for us is of course our IP address.

Find your IP address similar to where I have found mine, I have highlighted it for your convenience.

Finding Your IP Address

Python Script For Video Streaming

Finally, it is time to put the code in that will allow us to stream video from raspberry pi to our phone or any media devices for that matter.

We are going to write our streaming script on a python program file by the name rpi_stream_video_to_phone.py

You can of course change the name for your convenience.

To create the program file, use this command,

pi@raspberrypi:~ $ nano rpi_stream_video_to_phone.py

Next, you need to copy this script into this new file that you created. This code isn’t created by me but provided by the official PiCamera package documentation.

So, you can be assured that the code snippet if properly compiled and free of errors.

I mentioned in the beginning of this post that there are more than a few ways via which you can achieve the task of streaming video from raspberry pi to phone.

I am picking this method because I feel even beginners will be able to accomplish video streaming using the method we are discussing.

But if you need it, I will share an alternative way of streaming video from raspberry pi to, phone, tablet, or any media device of your choice.

It will be a bit more complicated for beginners but nevertheless, it is just as effective. Let me know in the comments section below.

Here is the code that you need to copy into your python program file.

import io
import picamera
import logging
import socketserver
from threading import Condition
from http import server

PAGE="""\
<html>
<head>
<title>Raspberry Pi Camera Streaming To Phone</title>
</head>
<body>
<h1>Raspberry Pi Live Streaming</h1>
<img src="stream.mjpg" width="640" height="480" />
</body>
</html>
"""

class StreamingOutput(object):
    def __init__(self):
        self.frame = None
        self.buffer = io.BytesIO()
        self.condition = Condition()

    def write(self, buf):
        if buf.startswith(b'\xff\xd8'):
            # New frame, copy the existing buffer's content and notify all
            # clients it's available
            self.buffer.truncate()
            with self.condition:
                self.frame = self.buffer.getvalue()
                self.condition.notify_all()
            self.buffer.seek(0)
        return self.buffer.write(buf)

class StreamingHandler(server.BaseHTTPRequestHandler):
    def do_GET(self):
        if self.path == '/':
            self.send_response(301)
            self.send_header('Location', '/index.html')
            self.end_headers()
        elif self.path == '/index.html':
            content = PAGE.encode('utf-8')
            self.send_response(200)
            self.send_header('Content-Type', 'text/html')
            self.send_header('Content-Length', len(content))
            self.end_headers()
            self.wfile.write(content)
        elif self.path == '/stream.mjpg':
            self.send_response(200)
            self.send_header('Age', 0)
            self.send_header('Cache-Control', 'no-cache, private')
            self.send_header('Pragma', 'no-cache')
            self.send_header('Content-Type', 'multipart/x-mixed-replace; boundary=FRAME')
            self.end_headers()
            try:
                while True:
                    with output.condition:
                        output.condition.wait()
                        frame = output.frame
                    self.wfile.write(b'--FRAME\r\n')
                    self.send_header('Content-Type', 'image/jpeg')
                    self.send_header('Content-Length', len(frame))
                    self.end_headers()
                    self.wfile.write(frame)
                    self.wfile.write(b'\r\n')
            except Exception as e:
                logging.warning(
                    'Removed streaming client %s: %s',
                    self.client_address, str(e))
        else:
            self.send_error(404)
            self.end_headers()

class StreamingServer(socketserver.ThreadingMixIn, server.HTTPServer):
    allow_reuse_address = True
    daemon_threads = True

with picamera.PiCamera(resolution='640x480', framerate=24) as camera:
    output = StreamingOutput()
    camera.start_recording(output, format='mjpeg')
    try:
        address = ('', 8000)
        server = StreamingServer(address, StreamingHandler)
        server.serve_forever()
    finally:
        camera.stop_recording()

Note that the resolution that we are using here is 640 X 480.

You can choose to have higher resolutions, however, there is a chance that your stream will show latency and stuttering.

It will depend to a great extent on the speed of your network, if you are streaming for the first time I recommend the same resolution that I am using.

You can increase it and see if you are receiving smoother frames at higher resolutions.

Once you have copied the code press Ctrl+X, type Y, and Enter. 

Starting The Video Stream

Once you have copied the piece of code that I have shown above, the next and the final thing that you need to do is running the script using python 3.

Use this command to run the script using python 3.

pi@raspberrypi:~ $ python3 rpi_stream_video_to_phone.py 

Once you ensure that the script is running, you will be able to access your video streaming on your phone by visiting, 

http://<RPI_IP_Address>:8000

You need to replace the RPI_IP_Address with the IP address you discovered previously.

You will be able to access this video stream not just from your phone but also from any device that has a browser provided the device is on the same network as your Raspberry Pi.

FAQs Regarding Raspberry Pi Streaming

If you have done everything the way I have listed here, you should be able to stream videos from raspberry pi to your phone or any other active device on your network.

Now streaming is just one use you can subject your Pi to.

The areas of applications are numerous and are expanding as we speak.

Manufacturers are trying to cram more resources into small form factors. I wouldn’t be surprised if the next iterations of the raspberry pi become even more potent.

Now limiting our discussions to Pi streaming in this article, I acknowledge, that even though I have tried to make the article comprehensive, some doubts and queries may still linger.

This is what this section is for.

I will expand this section organically to fit relevant queries as they come.

So, if you have any doubts, queries, or feedback, let me know in the comments section below.

If they are potent enough for the masses I will update them in this section with mention to the person who asked it.

Is Raspberry Pi Good For Streaming?

With the advanced hardware upgrades that the raspberry pi 4 is packed with like 8 GB RAM and the capacity to drive dual 4K displays, Raspberry Pi actually has become a very good streaming option. You can stream live videos, games, and videos from your favorite media-sharing platform.

Can Raspberry Pi Stream Netflix?

With hardware improvements that we have seen in Raspberry Pi 4, it can act as a competent second PC and you can even use it as a streaming and productivity device. With the Widevine Chromium support, you should be able to stream Netflix on Pi without any problem.

How Do I Use Raspberry Pi As A Streamer?

The newer version of Raspberry Pi 4 supports up to 8 GB of RAM and is capable of driving two 4K displays. This means for a streamer it opens up a range of applications. You can use it to stream games to your favorite device (steam link), stream live videos to your phone, or even use it to stream videos from your favorite content delivery platform like Netflix.

Electronics Engineer | Former Deputy Manager | Self-Taught Digital Marketer.Owner & Admin Of A Network Of Blogs and Global E-Commerce Stores

Pin It on Pinterest