Ozeki Camera Recorder Stat

How to display live Onvif IP camera image as Flash video on a website in C#

This example demonstrates a simple method for how you can connect your Console Application written in C# to an IP camera and how you can stream the image of the IP camera as Flash video on a website. To implement this example, you need to have OZEKI Camera SDK installed, and a reference to OzekiSDK.dll should be added to your Visual Studio project.

To be able to build this project properly you should peform the following steps:

  1. Building a webserver,
  2. Creating a new Visual Studio application written in C#,
  3. Launching both the webserver and the application,
  4. Finally checking the image of your IP camera on your internet browser.

How to setup a webserver?

In order to make a website work you will need a suitable webserver. For example you can use XAMPP (https://www.apachefriends.org/).

After installing the webserver with all its features the control panel of the application will appear:

How to setup XAMPP webserver
Figure 1 - How to setup XAMPP webserver

When you finished the installation process you should download the flash-based sources from our website and put all the contents which can be found in the compressed file into the htdocs folder. You can find the .rar file at the top of this page.

Please make sure that the first two services which you can see on the picture above are enabled. After enabling them you will be able to access your website in your browser.

You should verify that none of the other applications running on your computer use the same port number that is used by the running modules.

How to implement the C# application?

Important: you should study this article in order to find out how to setup your Console Application correctly. Please make sure that the SDK has been added as a reference to your Visual Studio project and that the project preferences have been set properly.

Getting started

To get started it is recomended to Download and Install the latest version of Ozeki Camera SDK. After installation you can find the example code discussed in this page with full source code in the following location on your harddisk:

Download Ozeki Camera SDK: http://www.camera-sdk.com/p_13-download-camera-onvif.html
Windows forms version: C:\Program Files\Ozeki\Ozeki SDK\examples.zip\Examples\Other\
Website_Display_Camera_Console\Website_Display_Camera_Console.sln

To compile this example you will need Microsoft Visual Studio installed on your computer.

You should also check the name of your Visual Studio project since using the same title could prevent further issues in connection with the namespaces of the application.

Besides the basic steps there is a new one in this project: you should create new source files within the project. To do this you should right-click on the name of the project in the Solution Explorer and choose the 'Add' > 'New Item' option: Visual C# Items / Class. Please name them to the titles you can see in the further part of this example and copy the codes in the right source files.

Please note that this example is about a Console Application instead of a Windows Forms Application. The image of the camera is not necessary to be in the application now that is why the console interface is enough.

Please note that this example can be divided into two parts: the console application mentioned above and the webserver mentioned at the top of the page. The code snippets below belong to the console application.

Please note that this example can work only when both parts are built properly and are running.

The important statements, classes and methods of this example are the following:

With the MyMediaGateway class your application will be able to establish a suitable connection between the C# Console Application and the webserver. When your application is running you can forward the captured image of the camera to the HTML interface of your website. This whole feature is based on the MyClient class that is used by the MyMediaGateway class for the implementation.

The MyClient class contains all the necessary methods and members to establish the connection with the IP camera and streams the image of the IP camera to the application.

The rest of the C# source code can be found in the flash content.

Finally in order to make your application work properly you should add one more new reference to your project in the Visual Studio IDE: System.Configuration. You can do this in the following way: please right-click on the References, choose the Add reference from the pop-up menu, then you should look up the mentioned reference on the .NET tab and add it to the other.

Implementing IP Camera Stream on Website in C#

MyMediaGateway.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Ozeki.MediaGateway;
using Ozeki.Media;
using Ozeki.Camera;


namespace Display_IP_Camera_Stream_On_Website
{
    public class MyMediaGateway : MediaGateway
    {
        private Dictionary<IClient, MyClient> clients;
        private IStreamService _streamService;

        public event EventHandler<EventArgs> ClientCountChange;

        public MyMediaGateway(MediaGatewayConfig config)
            : base(config)
        {
            clients = new Dictionary<IClient, MyClient>();
        }

        #region MediaGateway methods

        public override void OnStart()
        {
            base.OnStart();

            _streamService = GetService<IStreamService>();

            Console.WriteLine("MediaGateway started.");
        }

        public override void OnClientConnect(IClient client, object[] parameters)
        {
            Console.WriteLine(client.RemoteAddress + " client connected to the server with " + client.ClientType);
            if (clients.ContainsKey(client)) return;
            clients.Add(client, new MyClient(client, _streamService));
            ClientChange();
        }

        public override void OnClientDisconnect(IClient client)
        {
            var disconnectedClient = GetClient(client);
            if (disconnectedClient == null)
                return;

            disconnectedClient.DisconnectCamera();
            clients.Remove(client);
            ClientChange();
        }

        private void ClientChange()
        {
            var handler = ClientCountChange;
            if (handler != null)
                ClientCountChange(this, new EventArgs());
        }

        #endregion

        #region Client invokes

        public void CameraConnect(IClient client, string uri)
        {
            Console.WriteLine(client.RemoteAddress + " client IP camera connect " + uri);

            var myClient = GetClient(client);
            if (myClient == null)
                return;

            myClient.ConnectCamera(uri);
        }

        public void CameraDisconnect(IClient client)
        {
            Console.WriteLine(client.RemoteAddress + " client IP camera disconnect.");

            var myClient = GetClient(client);
            if (myClient == null)
                return;

            myClient.DisconnectCamera();
        }

        #endregion

        MyClient GetClient(IClient client)
        {
            return !clients.ContainsKey(client) ? null : clients[client];
        }
    }
}

Code 1 - MyMediaGateway.cs implementing IP Camera Streaming in C#

MyClient.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Ozeki.Media;
using Ozeki.Camera;
using Ozeki.MediaGateway;

namespace Display_IP_Camera_Stream_On_Website
{
    class MyClient
    {
        private IClient _client;
        private IStreamService _streamService;
        private IMediaStream _mediaStream;
        private MediaGatewayVideoReceiver _videoReceiver;
        private MediaConnector _connector;
        private IIPCamera _camera;

        public MyClient(IClient client, IStreamService streamService)
        {
            this._client = client;
            this._streamService = streamService;
            _connector = new MediaConnector();
        }

        internal void ConnectCamera(string uri)
        {
            // Connect to the camera
            if (String.IsNullOrEmpty(uri)) return;

            _camera = IPCameraFactory.GetCamera(uri, "admin", "admin");
            _camera.Start();

            if (_camera == null)
            {
                NotifyCameraStateChanged(IPCameraState.Error);
                return;
            }
            // Notify the client about the camera state
            NotifyCameraStateChanged(IPCameraState.Connected);

            // Start the stream
            var playStreamName = Guid.NewGuid().ToString();
            _mediaStream = _streamService.CreateStream(playStreamName);
            _videoReceiver = new MediaGatewayVideoReceiver(_mediaStream);

            _connector.Connect(_camera.VideoChannel, _videoReceiver);

            // Notify the client about the stream name
            OnPlayRemoteStream(playStreamName);
        }

        internal void DisconnectCamera()
        {
            if (_camera == null) return;
            _camera.Disconnect();

            _connector.Disconnect(_camera.VideoChannel, _videoReceiver);

            _videoReceiver.Dispose();
            _mediaStream.Close();

            NotifyCameraStateChanged(IPCameraState.Disconnected);
        }

        private void NotifyCameraStateChanged(IPCameraState state)
        {
            try
            {
                _client.InvokeMethod("OnCameraStateChanged", state);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

        void OnPlayRemoteStream(string streamName)
        {
            try
            {
                _client.InvokeMethod("OnPlayRemoteStream", streamName);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }
}

Code 2 - MyClient.cs implementing IP Camera Streaming in C#

Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Ozeki.Camera;
using Ozeki.Media;
using Ozeki.MediaGateway;

namespace Display_IP_Camera_Stream_On_Website
{
    class Program
    {
        static void Main(string[] args)
        {
            var config = new MediaGatewayConfig();
            config.AddConfigElement(new FlashConfig { ServiceName = "IPCameraServer" });

            MyMediaGateway _mediaGateway = new MyMediaGateway(config);
            _mediaGateway.Start();
            Console.Read();
        }
    }
}

Code 3 - Program.cs implementing IP Camera Streaming in C#

GUI

The Graphical User Interface of a website to which you can stream the Onvif IP camera image as a Flash video in C#
Figure 2 - The graphical user interface of your website

After installing the webserver, building the project and running them, the graphical user interface of your website will look like this.

DISCLAIMER: Please note that the following features will only work if your IP camera supports the given function. You should check the user manual of your IP camera to make sure it supports the feature that you wish to implement in C#.

Related Pages

FAQ

Below you can find the answers for the most frequently asked questions related to this topic:

  1. How can I get the URL of the camera?

    You can get the URL from the producer of the camera. (In the 10th tutorial you can find information on how to create an own IP camera discoverer program.)

  2. I have not managed to build the solution. How to solve it?

    • Please set the Target framework property of the project to .NET 4.0.
    • You should add the OzekiSDK.dll to the references of the solution.
    • Please import the missing classes.
  3. My Apache HTTP server does not work. Why?

    If you use Skype it occupies the port number 80 from Apache. Please close Skype.