wowza and streaming. lesson 9

id.241224001.472918

Lesson 9: Scheduling and Automating Stream Actions with Wowza REST API

This lesson focuses on automating tasks such as starting, stopping, and scheduling streams using the Wowza REST API, with examples in Node.js and Python.


Step 1: Prerequisites

  1. Enable REST API:

    • Ensure the REST API is enabled in Wowza Streaming Engine Manager.

    • Use a username and password for authentication.

  2. Install Required Libraries:

    • Node.js: Install axios.

        npm install axios
      
    • Python: Install requests.

        pip install requests
      

Step 2: Start and Stop Streams

Node.js Code: Start Stream

const axios = require('axios');

const wowzaApiUrl = 'http://<server-ip>:8087/v2';
const username = 'your-username';
const password = 'your-password';

async function startStream() {
    try {
        const response = await axios.put(
            `${wowzaApiUrl}/servers/_defaultServer_/vhosts/_defaultVHost_/applications/LiveStreamApp/instances/_definst_/streamfiles/MyStreamFile.stream/actions/connect`,
            {},
            {
                auth: { username, password },
                headers: { 'Content-Type': 'application/json' }
            }
        );
        console.log('Stream started:', response.data);
    } catch (error) {
        console.error('Error starting stream:', error.response.data);
    }
}

startStream();

Python Code: Start Stream

import requests
from requests.auth import HTTPBasicAuth

wowza_api_url = 'http://<server-ip>:8087/v2'
username = 'your-username'
password = 'your-password'

def start_stream():
    url = f"{wowza_api_url}/servers/_defaultServer_/vhosts/_defaultVHost_/applications/LiveStreamApp/instances/_definst_/streamfiles/MyStreamFile.stream/actions/connect"
    try:
        response = requests.put(url, auth=HTTPBasicAuth(username, password))
        if response.status_code == 200:
            print("Stream started:", response.json())
        else:
            print("Error:", response.status_code, response.json())
    except Exception as e:
        print("Error starting stream:", e)

start_stream()

Node.js Code: Stop Stream

async function stopStream() {
    try {
        const response = await axios.put(
            `${wowzaApiUrl}/servers/_defaultServer_/vhosts/_defaultVHost_/applications/LiveStreamApp/instances/_definst_/streamfiles/MyStreamFile.stream/actions/disconnect`,
            {},
            {
                auth: { username, password },
                headers: { 'Content-Type': 'application/json' }
            }
        );
        console.log('Stream stopped:', response.data);
    } catch (error) {
        console.error('Error stopping stream:', error.response.data);
    }
}

stopStream();

Python Code: Stop Stream

def stop_stream():
    url = f"{wowza_api_url}/servers/_defaultServer_/vhosts/_defaultVHost_/applications/LiveStreamApp/instances/_definst_/streamfiles/MyStreamFile.stream/actions/disconnect"
    try:
        response = requests.put(url, auth=HTTPBasicAuth(username, password))
        if response.status_code == 200:
            print("Stream stopped:", response.json())
        else:
            print("Error:", response.status_code, response.json())
    except Exception as e:
        print("Error stopping stream:", e)

stop_stream()

Step 3: Schedule Stream Actions

Scheduling can be done by integrating the Wowza API with a scheduling library in Node.js or Python.

Node.js Code: Schedule Stream

const schedule = require('node-schedule');

// Schedule to start the stream at a specific time
schedule.scheduleJob('0 10 * * *', function () { // At 10:00 AM
    console.log('Starting the stream...');
    startStream();
});

// Schedule to stop the stream at a specific time
schedule.scheduleJob('0 12 * * *', function () { // At 12:00 PM
    console.log('Stopping the stream...');
    stopStream();
});

Python Code: Schedule Stream

from apscheduler.schedulers.background import BackgroundScheduler

scheduler = BackgroundScheduler()

# Schedule to start the stream at 10:00 AM
scheduler.add_job(start_stream, 'cron', hour=10, minute=0)

# Schedule to stop the stream at 12:00 PM
scheduler.add_job(stop_stream, 'cron', hour=12, minute=0)

scheduler.start()

try:
    while True:
        pass  # Keep the script running
except (KeyboardInterrupt, SystemExit):
    scheduler.shutdown()

Step 4: Automate Stream Monitoring

Node.js Code: Monitor Stream

async function monitorStream() {
    try {
        const response = await axios.get(
            `${wowzaApiUrl}/servers/_defaultServer_/vhosts/_defaultVHost_/applications/LiveStreamApp/instances/_definst_/streamfiles/MyStreamFile.stream`,
            {
                auth: { username, password },
                headers: { 'Content-Type': 'application/json' }
            }
        );
        console.log('Stream details:', response.data);
    } catch (error) {
        console.error('Error monitoring stream:', error.response.data);
    }
}

setInterval(monitorStream, 60000); // Monitor every 60 seconds

Python Code: Monitor Stream

import time

def monitor_stream():
    url = f"{wowza_api_url}/servers/_defaultServer_/vhosts/_defaultVHost_/applications/LiveStreamApp/instances/_definst_/streamfiles/MyStreamFile.stream"
    try:
        response = requests.get(url, auth=HTTPBasicAuth(username, password))
        if response.status_code == 200:
            print("Stream details:", response.json())
        else:
            print("Error:", response.status_code, response.json())
    except Exception as e:
        print("Error monitoring stream:", e)

while True:
    monitor_stream()
    time.sleep(60)  # Monitor every 60 seconds

Example Use Case

  1. Scenario:

    • Start a stream at 10:00 AM and stop it at 12:00 PM.

    • Monitor the stream status every 60 seconds.

  2. Steps:

    • Use the scheduleStream function in Node.js or Python.

    • Automate the monitoring process to ensure the stream runs smoothly.


Next Steps:

  • Combine scheduling, monitoring, and notifications (e.g., email or Slack alerts) for advanced automation.

  • Integrate with third-party services for additional capabilities like logging or analytics.