How to Stream Truncated Audio Using MediaSource API

With a MediaSource API, we can generate and configure media streams right in a browser. It allows we to perform a accumulation of operations on media data hold by media-related HTML tags such as audio or video. For instance, we can mix opposite streams, create overlapping media, lazy bucket media, and edit media metrics such as change a volume or a frequency.

How to Display Timed Transcript Alongside Played Audio

How to Display Timed Transcript Alongside Played Audio

Audio twin is a content chronicle of speech, useful in providing useful materials like available lectures, seminars, etc.…Read more

In this post, we’ll privately see how to stream an audio sample (a truncated MP3 file) with a MediaSource API right in a browser in sequence to pre-show music to your audience. We will cover how to detect support for a API, how to connect a HTML media element to a API, how to fetch a media around Ajax, and finally how to stream it.

If we wish to see in allege what we are adult to, have a demeanour during a source formula on Github, or check out a demo page.

MediaSource APIMediaSource API

Step 1. Create a HTML

To emanate a HTML, supplement an audio tab with a controls attribute to your page. For back compatibility, also add a default blunder message for users whose browsers don’t support a feature. We will use JavaScript to spin on/off this message.

audio controls
Your browser doesn't support HTML audio element.
/audio

Step 2. Detect browser support

In JavaScript, emanate a try…catch block that will throw an error if a MediaSource API is not supported by a user’s browser, or, with other difference if MediaSource (the key) does not exist in a window object.

try {
  if (!'MediaSource' in window)
    chuck new ReferenceError('There is no MediaSource property
          in window object.')
  } locate (e) {
    console.log(e);
}

Step 3. Detect MIME support

After a support check, also check for a support of a MIME type. If a MIME form of a media we wish to tide is not upheld by a browser, alert a user and throw an error.

var mime = 'audio/mpeg';
if (!MediaSource.isTypeSupported(mime)) {
  alert('Can not play a media. Media of MIME form ' +
        mime + ' is not supported.');
  chuck ('Media of form ' + mime +
        ' is not supported.');
}

Note that a formula dash above needs to be placed inside a try block, before a catch retard (for reference, follow a line numbering or check out a final JS file on Github).

Step 4. Link a audio tab to a MediaSource API

Create a new MediaSource object, and assign it as a source of a audio tag by regulating a URL.createObjectURL() method.

var audio = document.querySelector('audio'),
mediaSource = new MediaSource();
audio.src = URL.createObjectURL(mediaSource);

Step 5. Add a SourceBuffer intent to MediaSource

When a HTML media component accesses a media source and is prepared to create SourceBuffer objects, a MediaSource API fires a sourceopen event .

The SourceBuffer intent holds a cube of media that is eventually decoded, processed and played. A singular MediaSource intent can have mixed SourceBuffer objects.

Inside a event handler of a sourceopen event, supplement a SourceBuffer intent to MediaSource with a addSourceBuffer() method.

mediaSource.addEventListener('sourceopen', function() {
  var sourceBuffer = this.addSourceBuffer(mime);
});

Step 6. Fetch a media

Now that we have a SourceBuffer object, it’s time to fetch a MP3 file. In a example, we’ll do so by using an AJAX request.

Use arraybuffer as responseType, that denotes binary data. When a response is successfully fetched, append it to SourceBuffer with a appendBuffer() method.

mediaSource.addEventListener('sourceopen', function() {
  var sourceBuffer = this.addSourceBuffer(mime);
  var xhr = new XMLHttpRequest;
  xhr.open('GET', 'sample.mp3');
  xhr.responseType = 'arraybuffer';
  xhr.onload = function() {
      try {
          switch (this.status) {
              box 200:
                sourceBuffer.appendBuffer(this.response);
                break;
              box 404:
                chuck 'File Not Found';
              default:
                chuck 'Failed to fetch a file';
         }
      } locate (e) {
        console.error(e);
      }
    };
    xhr.send();
});

Step 7. Indicate a finish of a stream

When a API has finished appending a information to SourceBuffer an event called updatend is fired. Inside an eventuality handler, call a endOfStream() process of MediaSource to indicate that a tide has ended.

mediaSource.addEventListener('sourceopen', function() {
  var sourceBuffer = this.addSourceBuffer(mime);
  var xhr = new XMLHttpRequest;
  xhr.open('GET', 'sample.mp3');
  xhr.responseType = 'arraybuffer';
  xhr.onload = function() {
    try {
      switch (this.status) {
        box 200:
            sourceBuffer.appendBuffer(this.response);
            sourceBuffer.addEventListener('updateend', duty (_){
                mediaSource.endOfStream();
            });
            break;
        box 404:
            chuck 'File Not Found';
        default:
            chuck 'Failed to fetch a file';
      }
    } locate (e) {
      console.error(e);
    }
  };
  xhr.send();
});

Step 8. Truncate a media file

The SourceBuffer intent has two properties called appendWindowStart and appendWindowEnd representing a start and finish time of a media data we wish to filter. The highlighted formula next filters a initial 4 seconds of a MP3.

mediaSource.addEventListener('sourceopen', function() {
  var sourceBuffer = this.addSourceBuffer(mime);
  sourceBuffer.appendWindowEnd = 4.0;
  ...
});

Demo

And that’s all, a audio representation is streamed right from a web page. For a source code, have a demeanour during a Github repo and for a final result, check out a demo page.

Browser support

As of essay this post, a MediaSource API is officially supported in all vital browsers. But a contrast shows that a implementation is cart in Firefox, and Webkit browsers still have troubles with a appendWindowStart property.

As a MediaSource API is still in a initial stage, entrance to aloft modifying functions might be singular though a basic streaming underline is something we can make use of right away.

Understanding Synchronous and Asynchronous JavaScript – Part 1

Understanding Synchronous and Asynchronous JavaScript – Part 1

Synchronous and asynchronous are treacherous concepts in JavaScript, generally for beginners. Two or some-more things are synchronous when…Read more

Add Comment