Showing posts with label stream. Show all posts
Showing posts with label stream. Show all posts

Web Audio API


Introduction:



           Audio on the web was never thought of without a flash or a plugin in the formative years. An excellent audio element of HTML 5 “The Web Audio API” has brought in a great revolution without the help of the above mentioned elements and is capable of supporting sophisticated games and interactive applications.

Web Audio API

             The Web Audio API is basically a high-level JavaScript API that processes and integrated audio in web apps.

       The two different types: In general there are two audio API’s one being the Audio data API and the other is the Web Audio API .The creation, the processing and the controlling of audio within the webapps is much simpler in Web Audio API when compared to the low-level access of the audio data by the Audio Data API.

        Amazing Feature: The attractive feature if that it does not require a helper application such as plug-in or flash. The main purpose of this API is to include the capabilities that are found in modern game audio engines and the excellent tasks such as mixing ,  processing and filtering tasks that are found in modern desktop audio production application.

The Working:

      The AudioContext instance: This is one of the most powerful instance used for managing and playing all the sounds. Initially an audio context has to be created which is like a container. Inside the context one can create sources and then connect them to the nodes and finally connected to the destination in the form a chain.


     var context = new AudioContext() ;
     //Audio Container created.


Since WebAudioAPI is a based on webkit technology and is supposed to be supported on IOS6,’webkit’ should be appended to the audio context.


var context = new WebKitAudioContext();


Once the audio context container is created a source node can also be created. A source node can be an Oscillator which generates sound from scratch or audio files such as wav, mp3 can be loaded and played back.

To create an oscillator


Oscillator = context.createOscillator();


Then the oscillator is supposed to be connected to the destination which can be speakers.


Oscillator.connect(context.destination);


To generate sound instantly


Oscillator.noteOn(0);


Now once the audio context is created between the source and the destination there is another interface called the audionode. They act as intermediate modules used for processing.

There are several audio nodes such as the-

1. Gainnode: This is used for volume which can be created in the following way-


volumeNode = context.createGainNode();


One can set the volume using


volumeNode.gain.value = 0.3;


Now this can be connected to the source


Oscillator.connect(volumeNode);


2. The Biquad filter: To add complex effects to your sound forms a biquad filter is used. It is low-order filter.

3. The delay node: It delays the incoming node signal.

4. The audiobuffer node: It consists of an in-memory audio data stored in an audio buffer.

5. Panner node: It describes its position with right –hand Cartesian co-ordinates and positions an incoming audio stream in 3D space.

6. Convolver node: Given an impulse response it applies a linear convolution effect.

7. Dynamic Compressor Node: When multiple sounds are played together, it helps to prevent distortion by lowering the volume of the loudest part of the signal.

8. Wave Shaper node: Inspite of the distortion effect, it applies a curve distorter to add a soothing feeling to the signal. It is a non-linear distorter.

By combining the above mentioned code one can find a working demo.

Exploring the WEB AUDIO API:


The AudioPara: It is like the AudioNode. It can be set to a specific value or a different value.

Ended: It is an event that can be called when the media has reached the end of the play.

The media elements:


MediaElementAudioSource Node: It is an audio node consisting of <audio> and <video> element of the HTML 5.

MediaStreamAudioSource Node: It is an audio node that acts as an audio source consisting of webcam or microphone.

MediaStreamAudioDestination Node: It is an audio node consisting of the audio destination node.

   How to extract time and frequency?

Then check out the Analyser node.
Assume that Source ‘S’ is connected to Destination ‘D’


var analyser = context.createAnalyser();
S.connect(analyser);
analyser.connect(D);
var freqDomain = new Float32Array(analyser.frequencyinCount);
analyser.getFloatFrequencyData(freqDomain);


A channel Splitter and a Merger?
A channel splitter separated different channels of an audio source into a set of mono outputs. It is created using a method called createChannelSplitter

A channel merger unites the mono inputs into a single output. It is created using a method called createChannelMerger

AudioListener: It gives the position and orientation of a person listening to the audio.

In c# it is created in the following way:


AudioListener listener = new AudioListener();


Script Process Node: This helps in the generation, processing or analysing of audio used in JavaScript.

Audio Process (event): When a script process node is ready to be processed the event is fired.

AudioProcessing Event: When the script processor node Input Buffer is ready to be processed, the event is fired.

Offline Audio Context: It does not render the audio but generates it as fast as it can in the buffer.

Complete: When the Offline Audio Context is terminated it is fired.

Offline Audio Completion Event: The complete event implements the interface.

Share your screen over Web(Screen sharing with HTML5)

A whole new concept on how a user can share his desktop or browser screens to other users is “Screen sharing” .
Is it possible?

While webRTC has not yet been supported by IE and Safari and these browsers  donot support screensharing  as well,there are several webapps that allow you and me to share the screens without the need of any plug-ins.The only one thing that is required to allow screen sharing is a browser called Chrome.Some of the webapps that support this screen sharing is same.io,talky.io and appear.in

Want to know how to do this in chrome?

Then follow the below steps-
  1.          Type chrome://flags in the address bar
  2.          You will find a setting like  “Enable screen capture support in getUserMedia()”
  3.          Click the enable button
  4.          Restart your browser.


Webapps like same.io and talky.io allows a user to share their screens. By allowing your chrome browser to access your web camera and microphone and by clicking on the “Share my Screen” button the user can share his screens.

Once the user hits that button the user will be provided with a unique web url and if anyone gets to know this url can access your screen through the chrome browser.

The other webapp talky.io allows private sessions wherein a user can protect his screens using a password.

Appear.in is a web app for video meetings that allows the user to share the desktop screen to other participants.




However a tech savvy guy named Rafael Weinstein has proposed a technique which uses Mutation observers and a websocket.

Let’s see how this works:

  1. The presenter shares his screen to the viewer using a websocket
  2. As the user performs any scroll operation the observer sends the changes and the report back to the viewer using Rafael mutation summary library.

Another method on how screensharing is done is:
  1. Rewrite all the pages on the URL to absolute to prevent static images and CSS elements from broken links
  2. Clone the page’s document
  3. Make the clone readonly, hidden and non-selectable and prevent scrolling.
  4. Capture the current position of the screen and add them as data-* attributes as duplicate
  5. Create a new BLOB page as duplicate.


The code for this is as follows-

 function screenshot(){
    urlsToAbsolute(document.images);  
    urlsToAbsolute(document.querySelectorAll("link[rel='stylesheet']"));
    urlsToAbsolute(document.scripts);

    var screen= document.documentElement.cloneNode(true);

    screen.style.pointerEvents = 'none';
    screen.style.overflow = 'hidden';
    screen.style.userSelect = 'none';

    var blob1 = new Blob([screen.outerHTML], {type: 'text/html'});

    window.open(window.URL.createObjectURL(blob1));
 }

   

Before the final BLOB is created this java script code should be written so that  when then presenter scrolls the page the user follows.

Set the scrollX and scrollY positions


 addOnPageLoad().
 screen.dataset.scrollX = window.scrollX;
 screen.dataset.scrollY = window.scrollY;


and finally write this below code –


 var script = document.createElement('script');
 script.textContent = '(' + addOnPageLoad_.toString() + ')();';.
 screenshot.querySelector('body').appendChild(script);
 function addOnPageLoad() {
    window.addEventListener('DOMContentLoaded', function(e) {
        var scrollX = document.documentElement.dataset.scrollX || 0;
        var scrollY = document.documentElement.dataset.scrollY || 0;
        window.scrollTo(scrollX, scrollY);
    });
 }


Another method is make the screenshot as a png file and share it using a websocket.

 var img_mimetype = 'images/jpeg';
 var IMG_QUALITY = 90;
 var SEND_INTERVAL = 280;
 var wes = new WebSocket('ws://...', 'sample-protocol');
 wes.binaryType = 'blob';
 function captureAndSendTab() {
    var opts = {format: img_mimetype, quality: IMG_QUALITY};
    chrome.tabs.captureVisibleTab(null, opts, function(dataUrl){
       wes.send(convertDataURIToBlob(dataUrl, IMG_MIMETYPE));
    });
  }
 var intervalId = setInterval(function() {
     if (ws.bufferedAmount == 0) {
         captureAndSendTab();
      }
    }, SEND_INTERVAL);


Conclusion:


Though without the use of WebRTC we have several technologies that help us to make screen sharing possible we still have to wait for the WebRTC to take a leap in making this screen sharing possible with HTML5 .

So guys wait to see the revolution that WebRTC is going to bring.

Javascript getUserMedia API

Capturing Audio and Video in HTML5: 


Earlier were the days when internet started that people started using chat as a medium of communication in the mid 90's. People used to capture audio or video and then send it over the internet.These features required the use of plugins like flash and Silverlight and these two had certain technical problems.

With the emergence of WebRTC the plugins has made its way out. One of the API that is derived from WebRTC is getUserMedia API.

Javascript getUserMedia API

 Get started with getUserMedia API:


Several multimedia streams such as video, audio and both can be accessed from local devices.The users need not use additional plugins to access the video or audio.It helps the non-technical user to use the software without any additional plugins.However this API allows users to acquire the video and audio without having to send the data or storing it in a file. This API uses one method called as method.getUserMedia() which belongs to the window.navigator object.

Syntax :

   navigator.getUserMedia(constraints,successCallback,errorCallback); 

Constraints: 


It has a constraints parameter which is an object that has two properties called audio and video. The properties contain two values true and false. True means to request the stream and false means do not request the stream.

 Example: to request only video the parameter is as follows


    { 
        Video:true, 
        Audio:false 
     } 
Example -2: If the user wants a high resolution of 1280x720 of both audio and video and if the frame rate is 30 and if we want a frame rate of 60 then the following code could be used

    { 
        video:{ 
            mandatory:{ 
                 minWidth:1280, 
                 minHeight:720, 
                 minFrameRate:30 
            }, 
            optional:[{minFrameRate :60}] 
         }, 
         audio:true 
     }

successCallback:


The function on the calling application to invoke when passing the LocalMediaStream object. The getUserMedia() will call the successCallback using the LocalMediaStream object.

 Example :

     function(localMediaStream) { 
          var myvideo=document.querySelector(‘video’); 
          myvideo.src=window.URL.createObjectURL(localMediaStream); 
          myvideo.onloadedmetadata=function() { 
                 //play or do something with the video. 
          };
     },  

errorCallBack: 


The getUserMedia() function will call the function called as errorCallback with error codes as follows-
Permission_denied: The user is denied the permission to use a media device required for the operation. Not_supported_error: A constraint specified is not supported by the browser. Mandatory_unsatisfied_error: If no media tracks of the type specified in the constraints are found an error occurs.

 To get permissions:


To get getUserMedia() installable on the app the following code should be embedded inside the file-

      “permissions”:{ 
            “audio-capture”:{ 
                  “description”:”required to capture audio via getUserMedia” 
              } 
        } 

Compatibility of the browser: 


The getUserMedia() API is supported by the desktop browser but it’s performance of mobile browser is poor.The current browsers that support this API are Chrome, Opera and Firefox.Some browsers also have a security issue such that upon calling the getUserMedia() API, the browsers give an option to the user saying that the user can grant/deny access to the camera/mic.

Conclusion:


The getUserAPI() derived from WebRTC project has worked wonders in making web applications successful.This API is very flexible allowing user to select its own parameters such as the audio and the video streams.The compatibility among the browsers is not very good but it would increase eventually.

Plugin less video call using webRTC

Introduction to WebRTC

WebRTC enables peer to peer communication using simple Javascript APIs. It supports to build rich, high quality, RTC applications using Javascript and HTML5. There Three APIs yet to develop RTC applications.
  1. Media Stream
  2. RTC Peer Connection
  3. RTC Data Channel


Getting started using getUserMedia

getUserMedia generates  MediaStream which receives Audio and Video from device. navigator.getUserMedia() gives mediastream having audio and video tracks. To get audio tracks from stream use stream.getAudioTracks() and to get stream.getVideoTracks(). 

getUserMedia takes three parameters constraints object, success callback and failure callback. The out received from the getUserMedia can be passed to RTCPeerConnection.

navigator.getUserMedia({ "audio": true, "video": true });

RTC Peer connection to exchanges streams

RTC peer connection API is to establish a persistent connection between peers. Rest of the process similar to video calling using WebRTC peer connection.

var signalChannel = createSignalingChannel();
var peerConn;
var config = ...;

// execute makeCall make a call
function makeCall(isCaller) {
    peerConn = new RTCPeerConnection(config);

    // sending ice candidates to the other peer
    peerConn.onicecandidate = function (evt) {
        signalChannel.send(JSON.stringify({ "candidate": evt.candidate }));
    };

    // set remote stream to the remote video element
    peerConn.onaddstream = function (evt) {
        remoteView.src = URL.createObjectURL(evt.stream);
    };

    // get the local stream and send
    navigator.getUserMedia({ "audio": true, "video": true }, function (stream) {
        selfView.src = URL.createObjectURL(stream);
        peerConn.addStream(stream);

        if (isCaller)
            peerConn.createOffer(gotDescription);
        else
            peerConn.createAnswer(peerConn.remoteDescription, gotDescription);

        function gotDescription(desc) {
            peerConn.setLocalDescription(desc);
            signalChannel.send(JSON.stringify({ "sdp": desc }));
        }
    });
}

signalChannel.onmessage = function (evt) {
    if (!peerConn)
        makeCall(false);

    var signalData = JSON.parse(evt.data);
    if (signalData.sdp)
        peerConn.setRemoteDescription(new RTCSessionDescription(signalData.sdp));
    else
        peerConn.addIceCandidate(new RTCIceCandidate(signalData.candidate));
};

How RTC Peer connection  descriptions exchange works?

  1. Peer1 runs the RTCPeerConnection createOffer() method. 
  2. The callback argument of this is passed an RTCSessionDescription: Peer1's local session description.
  3. In the callback, Peer1 sets the local description using setLocalDescription() and then sends this session description to Peer2 via their signaling channel. Note that RTCPeerConnection won't start gathering candidates until setLocalDescription() is called: this is codified in JSEP IETF draft.
  4. Peer2 sets the description Peer1 sent him as the remote description using setRemoteDescription().
  5. Peer2 runs the RTCPeerConnection createAnswer() method, passing it the remote description he got from Peer1, so a local session can be generated that is compatible with hers. 
  6. The createAnswer() callback is passed an RTCSessionDescription: Peer2 sets that as the local description and sends it to Peer1.
  7. When Peer1 gets Peer2's session description,  sets that as the remote description with setRemoteDescription.
  8. Both peers now having others streams.

Web RTC audio only Call


Introduction to WebRTC

WebRTC enables peer to peer communication using simple Javascript APIs. It supports to build rich, high quality, RTC applications using Javascript and HTML5. There Three APIs yet to develop RTC applications.
  1. Media Stream
  2. RTC Peer Connection
  3. RTC Data Channel

Getting started using getUserMedia


getUserMedia generates  MediaStream which receives Audio and Video from device. navigator.getUserMedia() gives mediastream having audio and video tracks. To get audio tracks from stream use stream.getAudioTracks() and to get stream.getVideoTracks(). 

getUserMedia takes three parameters constraints object, success callback and failure callback. The out received from the getUserMedia can be passed to RTCPeerConnection.

navigator.getUserMedia({ "audio": true, "video": true });

For audio call you just need to put false to video constraint.

navigator.getUserMedia({ "audio": true, "video": false });

RTC Peer connection to exchanges streams


RTC peer connection API is to establish a persistent connection between peers. Rest of the process similar to video calling using WebRTC peer connection.

var signalChannel = createSignalingChannel();
var peerConn;
var config = ...;

// execute makeCall make a call
function makeCall(isCaller) {
    peerConn = new RTCPeerConnection(config);

    // sending ice candidates to the other peer
    peerConn.onicecandidate = function (evt) {
        signalChannel.send(JSON.stringify({ "candidate": evt.candidate }));
    };

    // set remote stream to the remote video element
    peerConn.onaddstream = function (evt) {
        remoteView.src = URL.createObjectURL(evt.stream);
    };

    // get the local stream and send
    navigator.getUserMedia({ "audio": true, "video": false }, function (stream) {
        selfView.src = URL.createObjectURL(stream);
        peerConn.addStream(stream);

        if (isCaller)
            peerConn.createOffer(gotDescription);
        else
            peerConn.createAnswer(peerConn.remoteDescription, gotDescription);

        function gotDescription(desc) {
            peerConn.setLocalDescription(desc);
            signalChannel.send(JSON.stringify({ "sdp": desc }));
        }
    });
}

signalChannel.onmessage = function (evt) {
    if (!peerConn)
        makeCall(false);

    var signalData = JSON.parse(evt.data);
    if (signalData.sdp)
        peerConn.setRemoteDescription(new RTCSessionDescription(signalData.sdp));
    else
        peerConn.addIceCandidate(new RTCIceCandidate(signalData.candidate));
};


How RTC Peerconnection  descriptions exchange works?

  1. Peer1 runs the RTCPeerConnection createOffer() method. 
  2. The callback argument of this is passed an RTCSessionDescription: Peer1's local session description.
  3. In the callback, Peer1 sets the local description using setLocalDescription() and then sends this session description to Peer2 via their signaling channel. Note that RTCPeerConnection won't start gathering candidates until setLocalDescription() is called: this is codified in JSEP IETF draft.
  4. Peer2 sets the description Peer1 sent him as the remote description using setRemoteDescription().
  5. Peer2 runs the RTCPeerConnection createAnswer() method, passing it the remote description he got from Peer1, so a local session can be generated that is compatible with hers. 
  6. The createAnswer() callback is passed an RTCSessionDescription: Peer2 sets that as the local description and sends it to Peer1.
  7. When Peer1 gets Peer2's session description,  sets that as the remote description with setRemoteDescription.
  8. Both peers now having others streams.

HTML5: Recording Audio,Video Streams

HTML5: Recording Audio,Video Streams

MediaStreamRecorder API is webRTC API that supports recording streams with getUserMedia or remote streams passed over peerconnection session.



 
    <script language="javascript" type="text/javascript">
    function onVideoFail(e) {
        console.log('webcam fail!', e);
      };
 
    function hasGetUserMedia() {
      // Note: Opera is unprefixed.
      return !!(navigator.getUserMedia || navigator.webkitGetUserMedia ||
                navigator.mozGetUserMedia || navigator.msGetUserMedia);
    }
 
    if (hasGetUserMedia()) {
      // Good to go!
    } else {
      alert('getUserMedia() is not supported in your browser');
    }
 
    window.URL = window.URL || window.webkitURL;
    navigator.getUserMedia  = navigator.getUserMedia ||
                             navigator.webkitGetUserMedia ||
                              navigator.mozGetUserMedia ||
                               navigator.msGetUserMedia;
 
    var video = document.querySelector('video');
    var streamRecorder;
    var webcamstream;
 
    if (navigator.getUserMedia) {
      navigator.getUserMedia({audio: true, video: true}, function(stream) {
        video.src = window.URL.createObjectURL(stream);
        webcamstream = stream;
    //  streamrecorder = webcamstream.record();
      }, onVideoFail);
    } else {
        alert ('failed');
    }
 
    function startRecording() {
        streamRecorder = webcamstream.record();
        setTimeout(stopRecording, 10000);
    }
    function stopRecording() {
        streamRecorder.getRecordedData(postVideoToServer);
    }
    function postVideoToServer(videoblob) {
 
        var data = {};
        data.video = videoblob;
        data.metadata = 'test metadata';
        data.action = "upload_video";
        jQuery.post("uploadvideo.php", data, onUploadSuccess);
    }
    function onUploadSuccess() {
        alert ('video uploaded');
    }
 
    </script>
 



    <video autoplay></video>
    <div id="webcamcontrols">
        <button class="recordbutton" onclick="startRecording();">RECORD</button>
    </div>


"getRecorderdedData" return  blob that was recorded.


HTML5 Video Streaming: Media Source API

Streaming Video using HTML5 is now very simple, Media Source API gives streaming video as chunks. playing video with chunks of data is now possible.


This API allows to generate media streams, using  javascript streaming is enabled by extending HMTLElement.

<video id="video" src="" height="300" width="300">
      Video element is not supported in your browser
</video>




window.MediaSource = window.MediaSource || window.WebKitMediaSource;

var mediasource = new MediaSource();

var video = document.getElementById('video');
video.src = window.URL.createObjectURL(ms);

mediasource.addEventListener('webkitsourceopen', function(e) {
  ...
  var sourceBuffer = mediasource.addSourceBuffer('video/webm; codecs="vorbis,vp8"');
  sourceBuffer.append(oneVideoWebMChunk);
  ...
//start playing after video header recieved(i.e; first chunk)
//call media.endOfStream(); before appending last chunk
}, false);

playing large volume media files is a bit hard, just make them as chunks and stream with video element. Remember that Video file header contains vital information to play video, this should be necessary to seek and play stream video. if you want to play video from a segment you should first load video fie header then load the segment data to stream your data.

you start playing the stream after receiving header only.

Media Source API now works only chrome( set --enable-media-source flag ).
Media Source Extensions specification changed, changes expected to be made in next release.