Tutorials · 4 min read

now serving 25

Count your live stream viewers with api.video

When you're live streaming - you want your viewers to know how many others are watching. This demo shows you how to build a counter for your live stream!

Doug Sillars

July 22, 2021

One of the most satisfying features of livestreaming is seeing a live counter of how many people are watching your live stream. In this demo, we’ll build a counter that gives a real time count of the number of viewers watching a live stream.

api.video livestreams

Each livestream at api.video can be used over and over. It is a conduit for your livestreams. There is a RTMP url that you use to send your livestream to api.video, and a playback url that you can embed in your website. When you look at a livestream on your api.video dashboard, you’ll see all the connection details (some are obfuscated in the screenshot) to connect your livestream.

viewer count of video

The viewer count of a video

Right underneath the thumbnail of the livestream, you can see a viewer count. In the screenshot above it is at 632. That is the count of historical views for this livestream - a sum of all the views for every livestream that has been run. While this is an interesting stat, this is not exactly what we want to see during a livestream.

This NodeJS function takes your liveStreamId, and calls the analytics endpoint to get the total number of sessions that have occurred for that live stream:

function getLiveSessionCount(liveStreamId){
 
   return new Promise(function(resolve, reject){
       console.log(liveStreamId);
       var pageSize=1;
       var currentPage = 1;
       params = {
           "liveStreamId": liveStreamId,
           "pageSize":pageSize,
           "currentPage":currentPage
       }
       //get all sessions for livestream
       var sessionList = client.rawStatistics.listLiveStreamSessions(params);
       sessionList.then(function(liveSessionList){
           //get total sessoin
           var sessionCount = liveSessionList.pagination.itemsTotal;
           console.log("live sessions" , sessionCount);
           resolve(sessionCount);
       }).catch((error) =>{
           reject(error);
       });
   });
}

Counting the views

To get an accurate count of viewing sessions during a livestream, we need to grab the livestream count when the stream starts (all of the views PRIOR to the current stream). As the stream progresses, the number will increase, but a simple difference currentCount - startCount will provide the number of sessions that occurred during the current stream.

Live stream webhooks

In July 2021, we launched 2 new webhooks: live-stream.broadcast.started and live-stream.broadcast.ended. These webhooks announce whenever one of your live streams begin/end broadcasting.

When the live-stream.broadcast.started webhook fires, our webhook listener identifies that a live stream has started. Then it calls the getLiveSessionCount function to get the starting count of sessions.

app.post("/receive_webhook", function (request, response) {
   console.log("new video event from api.video");
    let event = request.body;
   let body =request.body;
   let type = body.type;
   let emittedAt = body.emittedAt;
   webhookResponse = "";
   if(type =="live-stream.broadcast.started"){
       liveStreamId = body.liveStreamId;
       liveStreamStatus = true;
       webhookResponse = "event: " +type+ " at: "+ emittedAt+ " LiveStream,Id: "+liveStreamId+ "  has started.";
      
       //change the broadcasting status in the JSON pbject
       broadcastingStatus[liveStreamId]=liveStreamStatus;
       //TODO - get the number of views at start
       startViews = getLiveSessionCount(liveStreamId);
       startViews.then(function(startcounter){
           console.log("number of views when broadcast starts", startcounter);
           viewersAtStartOfStream[liveStreamId] = startcounter;
           webhookResponse = "event: " +type+ " at: "+ emittedAt+ " LiveStreamId: "+liveStreamId+ "  has started. There have been "+startcounter+" at the beginnig";
 
       });
      
    } else if (type =="live-stream.broadcast.ended"){
       liveStreamId = body.liveStreamId;
       liveStreamStatus = false;
       broadcastingStatus[piLiveId]=liveStreamStatus;
       webhookResponse = "event: " +type+ " at: "+ emittedAt+ " LiveStreamId: "+liveStreamId+ "  has stopped.";
    }
  
   //console.log(headers);
   console.log("response",webhookResponse);
 
  
   response.sendStatus(200); 
 });


Now, as the streaming progresses, the website polls /getLivecount every three seconds:

// Send list of the new count of viewers every x seconds
app.get("/getLivecount", function (request, response) {
 
 
   var LiveId = request.query.live;
   console.log("LiveId", LiveId);
   console.log(viewersAtStartOfStream);
   startCount = viewersAtStartOfStream[LiveId];
   console.log("startCount", startCount);
   //we have liveid get new user count
   var currentCount = getLiveSessionCount(LiveId);
           currentCount.then(function(currentWatchCount){
 
               console.log(startCount + " " + currentWatchCount);
               numberOfWatchers = currentWatchCount - startCount;
               console.log("numberOfWatchers", numberOfWatchers);
               response.send("There are " +numberOfWatchers + " watching this stream!");
           }).catch((err) => {
               console.log(err);
           });
 });

And this returns the difference from the start of stream (stored in an array on the server), and the current count. Voila, a simple view counter!

Conclusion

In this demo, when the live stream begins broadcasting, we utilize the live stream started webhook, which broadcasts that the stream has started. We determine the ‘seed’ number of sessions using the Live stream session analytics. Now we know the “0” for this live streaming session.

We can call the same endpoint every 3 seconds and report the growth in the number of sessions. Each one of these is a new loading of the live stream video player - counting as a new viewer of the stream. This is then added to the page to indicate how many viewers are watching the live stream.

This demo is live at watch.a.video/broadcast. To begin the stream, head over to livestream.a.video and begin the stream. To grow the number of viewers, you must open watch.a.video/broadcast in multiple incognito/private browser tabs (since the session is browser window based).

Try it out, and tell us what you think! If you’d like to look at the code to modify for your app, it is live on Github.

Try out more than 80 features for free

Access all the features for as long as you need.
No commitment or credit card required

Video API, simplified

Fully customizable API to manage everything video. From encoding to delivery, in minutes.

Built for Speed

The fastest video encoding platform. Serve your users globally with 140+ points of presence. 

Let end-users upload videos

Finally, an API that allows your end-users to upload videos and start live streams in a few clicks.

Affordable

Volume discounts and usage-based pricing to ensure you don’t exceed your budget.