Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <!DOCTYPE html>
<!-- nanoStream WebRTC Webcast / Broadcast to RTMP
     (c) 2014-2020 nanocosmos gmbh, All rights reserved
     http://www.nanocosmos.de 
     V 2020-12-01
Test instruction: add your bintu api key to the code below or the browser url, 
like https://codepen.io/url?bintu.apikey=XXXXX
-->
<html>

<head>
  <title>nanoStream Cloud Webcaster minimal broadcast sample</title>

  <!-- nanoStream Cloud  bintu API -->
  <script src="https://webrtc.nanocosmos.de/webrtc-api/5/nano.bintu.min.js"></script>

  <!-- nanoStream Cloud Webcaster API -->
  <script src="https://webrtc.nanocosmos.de/webrtc-api/5/nano.webrtc.min.js"></script>

  <!-- default webcaster app configuration -->
  <script src="https://webrtc.nanocosmos.de/release/js/app/nano.config.js"></script>

  <script>
    // global nano variables
    var user, config, bintu, bintuApiKey, bintuTags, playoutURL, token;

    // global entry point for this sample
    nanoStream_init = function() {
      console.log("nanoStream_init");
      // Config/Authentication
      // for your own custom version you may add your config here or in config.js
      config = window.NANOCONFIG; // Included above (nano.config.js)
      bintuApiKey = config.bintu.apikey; // required: your custom API key
      // token is optional
      var token = config.webrtc.token ?
        encodeURIComponent(JSON.stringify(config.webrtc.token)) : '';
      if (token == "" && bintuApiKey == "") {
        showError("bintu api key missing- add your bintu api key to the code or url, like ?bintu.apikey=XXXXX")
      }      
      
      nanoStream_bintu_init();
      nanoStream_Webcaster_init();

    };
    
    nanoStream_Webcaster_init = function() {
      // Initialize nanoStream Webcaster to connect your webrtc webcam or screen
      // Create rtc user
      user = new window.nanowebrtc.user();
      if (!user) {
        showError("Could not init nanowebrtc.user - include correct api?");
      }
      nano_registerEvents(user);
      var server = config.webrtc.server;
      user.signIn({
        server: server,
        token: token,
        bintuApiKey: bintuApiKey
      });
    };
    
    // Webcaster: start camera and microphone (getusermedia)
    nano_startCam = function() {
      if (!user) {
        logStatus('No rtcUser, please "init" first');
      }
      // Get camera and microphone and start preview
      user.getDevices();
      user.on('ReceivedDeviceList', function(event) {
        var videoElement = "video-local"; // HTML <video id=...>
        // Available devices (cam/mic)
        var audioDevices = event.data.devices.audiodevices;
        var videoDevices = event.data.devices.videodevices;
        var videoDeviceConfig = {
          device: false // video disabled by default, set to 0 to force using it
        };
        var audioDeviceConfig = {
          device: false // audio disabled by default, set to 0 to force using it
        };
        var camName = "None",
          micName = "None";
        var camIndex = 0,
          micIndex = 0; // choose first cam/mic device found
        if (videoDevices.length > 0) {
          // configure camera
          videoDeviceConfig.device = camIndex;
          //videoDeviceConfig.width = 640;
          //videoDeviceConfig.height = 480;
          //videoDeviceConfig.framerate = 25;
          camName = videoDevices[camIndex].id;
          console.log("Using Camera " + camName);
        } else {
          // you might throw an error here.
          console.log("Error: No camera found.");
        }
        if (audioDevices.length > 0) {
          // configure microphone
          audioDeviceConfig.device = micIndex;
          micName = audioDevices[micIndex].id;
          console.log("Using Microphone " + micName);
        } else {
          // you might throw an error here.
          console.log("Error: No microphone found.");
        }
        console.log("Starting Preview");
        var config = {
          videoDeviceConfig: videoDeviceConfig,
          audioDeviceConfig: audioDeviceConfig,
          elementId: videoElement
        };
        user.startPreview(config);
      });
    };
    
    // Register nano API event handlers
    nano_registerEvents = function(user) {
      // sign in success/error
      user.on("SignInSuccess", function(event) {
        logStatus("Webcaster SignInSuccess");
      });
      user.on("SignInError", function(event) {
        logStatus("Webcaster SignInError");
      });
      // cam preview success/error
      user.on('StartPreviewSuccess', function(event) {
        logStatus("Camera/Microphone started", event);
      });
      user.on('StartPreviewError', function(event) {
        showError("Camera/Microphone error", event.data.text);
      });
      // stop  broadcast success/error
      user.on('StopBroadcastSuccess', function(event) {
        logStatus("BroadcastStatus: Stopped.");
      });
      user.on('StopBroadcastError', function(event) {
        logStatus(event.data.text);
      });
      // start broadcast success/error
      user.on('StartBroadcastSuccess', function(event) {
        logStatus("Webcaster StartBroadcastSuccess", event);
      });
      user.on('StartBroadcastError', function(event) {
        showError(event.data.text);
      });
      // server error during streaming
      user.on('ServerError', function(event) {
        logStatus(event.data.text);
        nano_error_broadcast();
      });
      // broadcast error during streaming
      user.on('BroadcastStatus', function(event) {
        var broadcastStatus = "";
        if (event && event.data && event.data.text) {
          broadcastStatus = event.data.text;
          logStatus("BroadcastStatus: " + broadcastStatus);
          if (broadcastStatus === 'disconnected') {
            nano_error_broadcast();
          }
        } else {
          logStatus("BroadcastStatus", event);
        }
      });
    };
    
    // error during broadcast: show error and cleanup
    nano_error_broadcast = function() {
      user.stopBroadcast();
      user.signOut();
      showError("Broadcast disconnected. Please try again.");
    };
    nano_setStreamAndPlaybackInformation = function(stream) {
      ingest = stream.ingest;
      playoutURL = 'https://demo.nanocosmos.de/nanoplayer/release/nanoplayer.html?bintu.apiurl=' + config.bintu.apiurl + '&bintu.streamid=' + stream.id;
      logStatus('Stream Info: ' + 'Ingest: ' + JSON.stringify(stream.ingest) + ' ID: ' + stream.id + ' Playout URL: ' + playoutURL);
    };
    
    // bintu functions for stream management
    
    // init nanoStream apis
    nanoStream_bintu_init = function() {
      // Initialize nanoStream Cloud (Bintu) to obtain a live stream 
      var bintuApiUrl = config.bintu.apiurl || "https://bintu.nanocosmos.de";
      bintu = new Bintu(bintuApiUrl, bintuApiKey, true, false);
      // optional bintu tags, you can freely modify
      var myBintuTag = "12345_abcde"
      bintuTags = [myBintuTag]; 
      playoutURL = '';      
    };
    
    
    // create bintu ingest stream to send a live stream 
    var ingest; // (global) takes the ingest stream info
    nano_createStream = function() {
      var bintuStreamId = config.bintu.streamid;
      // do we have already a bintu stream?
      if (bintuStreamId) {
        logStatus("Getting existing Bintu stream");
        nano_getStream(bintuStreamId);
      } else {
        logStatus("Creating a new Bintu stream");
        bintu.createStream(bintuTags, function success(request) {
          var stream = JSON.parse(request.responseText);
          nano_setStreamAndPlaybackInformation(stream);
        }, function onerror(result) {
          if (result.request && result.request.response)
            logStatus(result.request.response);
          else
            logStatus(error);
        });
      }
    };
    
    // get bintu stream object for existing stream
    nano_getStream = function(streamid) {
      logStatus("Getting info for Bintu stream " + streamid);
      bintu.getStream(streamid, function success(request) {
        var stream = JSON.parse(request.responseText);
        nano_setStreamAndPlaybackInformation(stream);
      }, function onerror(result) {
        if (result.request && result.request.response)
          logStatus(result.request.response);
        else
          logStatus(error);
      });
    };
    
    // start broadcast to bintu / nanoStream Cloud
    nano_startBroadcast = function() {
      if (!ingest) {
        showError("no ingest stream url");
        return;
      }
      var rtmp = ingest.rtmp;
      var url = rtmp.url;
      var streamname = rtmp.streamname;
      var broadcastConfig = {
        transcodingTargets: {
          output: url,
          streamname: streamname,
          framerate: 25,
        }
      };
      logStatus("Starting Broadcast");
      user.startBroadcast(broadcastConfig);
    };
    
    nano_stopBroadcast = function() {
      if (user)
        user.stopBroadcast();
    };
    
    // UI/button event handlers
    nano_registerUI = function() {
      document.getElementById('btn-init').addEventListener('click', function() {
        nanoStream_init();
      });
      document.getElementById('btn-startcam').addEventListener('click', function() {
        nano_startCam();
      });
      document.getElementById('btn-createstream').addEventListener('click', function() {
        nano_createStream();
      });
      document.getElementById('btn-startbroadcast').addEventListener('click', function() {
        nano_startBroadcast();
      });
      document.getElementById('btn-stopbroadcast').addEventListener('click', function() {
        logStatus("Stopping broadcast");
        nano_stopBroadcast();
      });
      document.getElementById('btn-playh5livestream').addEventListener('click', function() {
        console.log("Opening new window to play live stream, URL: ", playoutURL);
        window.open(playoutURL, '_blank');
      });
    };
    
    // log message to console and status element
    logStatus = function(msg, event) {
      if (event) {
        msg = msg + " - " + JSON.stringify(event);
      }
      document.getElementById("status").textContent = msg;
      console.log(msg);
    };
    // show error alert
    showError = function(errorMessage) {
      alert(errorMessage)
    };
    // close/stop on unload page
    window.onbeforeunload = function(event) {
      nano_stopBroadcast();
    };
  </script>

</head>

<body>
  <h1>nanoStream Cloud Webcaster</h1>
  <h2>minimal broadcast sample connected to nanoStream Cloud</h2>
  <p>This sample creates a live stream with bintu.live and WebRTC.live and creates a player URL to for nanoStream H5Live Player.
  </p>
  <!-- Video element for camera preview -->
  <video id="video-local" class="remote-element-video" autoplay playsinline muted style="width:320;height:240"></video>
  <hr>
  <!-- Buttons start/stop/play -->
  <button id="btn-init">init</button>
  <button id="btn-startcam">start cam</button>
  <button id="btn-createstream">create stream</button>
  <button id="btn-startbroadcast">start broadcast</button>
  <button id="btn-stopbroadcast">stop broadcast</button>
  <button id="btn-playh5livestream">play h5live stream</button>
  <hr>
  <span id="status">stopped</span>

  <script>
    nano_registerUI();
  </script>
</body>

</html>
              
            
!

CSS

              
                
              
            
!

JS

              
                
              
            
!
999px

Console