Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.

+ 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

Auto Save

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

              
                <p>Try simulating a 3G connection in Chrome DevTools' Network tab to see the buffering mechanism in action</p>

<div class="media-container">
  <video src="https://storage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4" controls></video>
  <audio src="https://github.com/rafaelreis-hotmart/Audio-Sample-files/raw/master/sample.mp3" controls></audio>
</div>

<button class="play">play</button>
<button class="stop">clear</button>

              
            
!

CSS

              
                video, audio {
  width: 300px;
}
              
            
!

JS

              
                /* withBuffering */

const BUFFERING_EVENT_NAME_LIST = ['canplay', 'waiting', 'loadstart'];

let buffered = [];
let bufferCheckIntervalId = -1;

const bufferingSymbol = Symbol('handleBuffering');

const withBuffering = (controller, mediaContainer) => {
  const alreadyHandled = mediaContainer[bufferingSymbol];
  if (alreadyHandled) {
    return;
  }

  mediaContainer[bufferingSymbol] = true;

  BUFFERING_EVENT_NAME_LIST.forEach(eventName =>
    mediaContainer.addEventListener(
      eventName,
      ({ target: mediaElement }) =>
        isHTMLMediaElement(mediaElement) &&
        tryBuffering(controller, mediaElement),
      { capture: true },
    ),
  );
};

const tryBuffering = (controller, mediaElement) => {
  const noNeedBuffering =
    !controller.isPlay ||
    isMediaPlayable(mediaElement) ||
    buffered.includes(mediaElement);

  if (noNeedBuffering) {
    return;
  }

  const preventPlay = () => {
    controller.pause();
  };

  preventPlay();
  mediaElement.addEventListener('playing', preventPlay);
  buffered.push(mediaElement);

  startCheckMediaIsPlayable(() => {
    clearBuffer(preventPlay);
    controller.play();
  });
};

const CHECK_INTERVAL_MS = 3000;

const startCheckMediaIsPlayable = onPlayable => {
  if (bufferCheckIntervalId !== -1) {
    return;
  }

  const executeOnPlayableWhenEveryPlayable = () => {
    const everyPlayable = buffered.every(isMediaPlayable);
    if (everyPlayable) {
      onPlayable();
      return;
    }

    bufferCheckIntervalId = setTimeout(
      executeOnPlayableWhenEveryPlayable,
      CHECK_INTERVAL_MS,
    );
  };

  executeOnPlayableWhenEveryPlayable();
};

const clearBuffer = preventPlay => {
  window.clearTimeout(bufferCheckIntervalId);
  bufferCheckIntervalId = -1;
  buffered.forEach(element =>
    element.removeEventListener('playing', preventPlay),
  );
  buffered = [];
};

const isHTMLMediaElement = element => element instanceof HTMLMediaElement;

const isMediaPlayable = mediaElement => {
  if (mediaElement.networkState !== mediaElement.NETWORK_LOADING) {
    return true;
  }

  if (mediaElement.readyState >= mediaElement.HAVE_ENOUGH_DATA) {
    return true;
  }

  return false;
};

/* UI */

document.addEventListener('DOMContentLoaded', () => {
  const mediaContainer = document.querySelector('.media-container');
  const videoElement = document.querySelector('video');
  const audioElement = document.querySelector('audio');

  const controller = {
    isPlay: false,
    play() {
      this.isPlay = true;
      videoElement.play().catch(e => console.log('Failed to play video:', e));
      audioElement.play().catch(e => console.log('Failed to play audio:', e));
    },
    stop() {
      this.pause();
      clearMedia(videoElement);
      clearMedia(audioElement);
    },
    pause() {
      this.isPlay = false;
      videoElement.pause();
      audioElement.pause();
    },
  };

  withBuffering(controller, mediaContainer);

  document
    .querySelector('button.play')
    .addEventListener('click', () => controller.play());
  document
    .querySelector('button.stop')
    .addEventListener('click', () => controller.stop());
});

const clearMedia = mediaElement => {
  mediaElement.currentTime = 0;

  const originSrc = mediaElement.src;
  mediaElement.src = '';
  mediaElement.load();
  mediaElement.src = originSrc;
};

              
            
!
999px

Console