# HTML5 Video & Audio

  • Built in support for playing audio and video in the browser without plugins like flash or silverlight
    内置支持在浏览器中播放音频和视频,不需要像 flash 或 silverlight 这样的插件
  • Uses the <video> or <audio> tag for basic support.
  • Traditionally format/codec support was mixed between browser manufacturers, and we needed to supply different formats
    传统上,浏览器厂商对格式 / 编解码器的支持是混合的,我们需要提供不同的格式
  • As of 2016 h.264 mp4 and mp3 is supported in most browsers
  • In Oct 2013 Cisco announced they would make a h.264 module available to all
  • You can provide fallback content inside the tag if the browser doesn't support it
    如果浏览器不支持,您可以在标记内提供备用内容
  • There are attributes for controls, autoplay, loop, preload. See element docs
    • https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Using_HTML5_audio_and_video
    • https://developer.mozilla.org/en-US/docs/Web/HTML/Supported_media_formats

# <source> tag

The <source> tag can be nested inside the <video> or <audio> tag to supply multiple formats

<video src="http://v2v.cc/~j/theora_testsuite/320x240.ogg" controls>
    <p>Your browser does not support the <code>video</code> element.</p>
</video>
<video controls>
    <source src="SampleVideo.ogv" type="video/ogv">
    <source src="SampleVideo.mp4" type="video/mp4">
    <p>Your browser does not support the <code>video</code> element.</p>
</video>
  • The <video> and <audio> elements have methods attached for controlling
    playback
  • https://www.html5rocks.com/en/tutorials/video/basics/

# DEMO

audio
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>HTML5 Audio</title>
</head>
<body>
	<audio id="audiosrc" src="BrahmsSymphony-fromFourthMovement.mp3" controls></audio>
</body>
</html>
video
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>HTML5 Video</title>
</head>
<body>
	<button id="btn">Play</button>
	<button id="btn-stop">Pause</button>
	<video id="vid" controls> 
	  <source src="small.webm" type="video/webm"> 
	  <source src="small.ogv" type="video/ogg"> 
	  <source src="small.mp4" type="video/mp4">
	  <source src="small.3gp" type="video/3gp">
	</video>
	
	<script>
		document.getElementById('btn').addEventListener('click', function(){
			document.getElementById('vid').play();
		});
		document.getElementById('btn-stop').addEventListener('click', function(){
			document.getElementById('vid').pause();
		});
		document.getElementById('vid').addEventListener('ended', function(e){
			console.log(e);
			alert('video is finished');
		});
	</script>
</body>
</html>

# Geolocation

  • The geolocation API allows the user to provide their location to web applications if they so desire.
    如果用户愿意,地理位置 API 允许用户向 web 应用程序提供他们的位置。
    For privacy reasons, the user is asked for permission to report location information.
    出于隐私考虑,用户需要获得报告位置信息的许可。

  • The API is published through the navigator.geolocation object
    API 是通过 navigator.geolocation 发布的对象

  • getCurrentPosition() method is used to query the browser for a location object
    getCurrentPosition() 方法用于在浏览器中查询一个位置对象

  • Takes a callback function that runs when the browser responds with a location and also takes an optional second callback function to run if there is an error
    接受一个回调函数,该函数在浏览器响应一个位置时运行,也接受一个可选的第二个回调函数,在出现错误时运行

  • watchPosition() method can be used to continually update the position
    watchPosition() 方法可用于持续更新位置

  • https://developer.mozilla.org/en-US/docs/Web/API/Geolocation_API/Using_the_Geolocation_API

navigator.geolocation.getCurrentPosition(function(position) {
    do_something(position.coords.latitude, position.coords.longitude);
});

# DEMO

geolocation
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Basic Geolocation</title>
    <script>
        let options = {
            enableHighAccuracy: true,
            timeout: 5000,
            maximumAge: 0
        };
        function success(pos) {
            let crd = pos.coords;
            console.log('Your current position is:');
            console.log(`Latitude : ${crd.latitude}`);
            console.log(`Longitude: ${crd.longitude}`);
            console.log(`More or less ${crd.accuracy} meters.`);
            let wrapper = document.createElement('div');
            let text = `Your current position is: <br>
            Latitude: ${crd.latitude}<br>
            Longitude: ${crd.longitude}<br>
            More or less ${crd.accuracy} meters.`;
            wrapper.innerHTML = text;
            document.getElementsByTagName('body')[0].appendChild(wrapper);
        }
        function error(err) {
            console.warn(`ERROR(${err.code}): ${err.message}`);
            let wrapper = document.createElement('div');
            let text = `Error(${err.code}): ${err.message}`;
            wrapper.innerHTML = text;
            document.getElementsByTagName('body')[0].appendChild(wrapper);
        }
        navigator.geolocation.getCurrentPosition(success, error, options);
    </script>
</head>
<body>
    
</body>
</html>
geolocation basic
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<script type="text/javascript">
		function success(p){
			console.log(p);
			alert('Lat: ' + p.coords.latitude + ', Long: ' + p.coords.longitude);
			document.getElementsByTagName('body')[0].appendChild(document.createTextNode('Lat: ' + p.coords.latitude + ', Long: ' + p.coords.longitude));
		}
		function error(e){
			console.log(e);
			alert('Error: ' + e.message);
		}
		navigator.geolocation.getCurrentPosition(success, error);
		
	</script>
</head>
<body>
	
</body>
</html>
geolocation map
<!DOCTYPE html>
<html>
  <head>
    <title>Simple Map</title>
    <script src="https://maps.googleapis.com/maps/api/js"></script>
    <style type="text/css">
      #map {
        height: 100%;
      }
      html,
      body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
    </style>
  </head>
  <body>
    <div id="map"></div>
    <script type="text/javascript">
      navigator.geolocation.getCurrentPosition(function(p){
        console.log(p);
        
        let map = new google.maps.Map(document.getElementById('map'), {
          center: {
            lat: p.coords.latitude,
            lng: p.coords.longitude
          },
          zoom: 14
        });
        let marker = new google.maps.Marker({
          map: map,
          position: {
            lat: p.coords.latitude,
            lng: p.coords.longitude
          }
        });
      });
    </script>
  </body>
</html>

# Web Workers

  • Web Workers provide a simple way for web applications to run scripts in background threads.
    Web Workers 为 Web 应用程序在后台线程中运行脚本提供了一种简单的方法。
    Basically, adds a multithreading model to JavaScript
    基本上,就是在 JavaScript 中添加一个多线程模型
  • The worker threads do not block or interfere with the user interface or main thread
    工作线程不会阻塞或干扰用户界面或主线程
  • The main script and worker scripts post messages to each other and can pass standard JavaScript data between each other.
    主脚本和辅助脚本相互发送消息,并可以相互传递标准的 JavaScript 数据。
    • This is done with the postMessage() method and the onmessage event
      这是通过 postMessage() 方法和 onmessage 事件完成的
  • https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers
  • http://www.html5rocks.com/en/tutorials/workers/basics/
  • https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API
  • https://github.com/michaeltreat/Web-Worker-Demo
  • https://en.wikipedia.org/wiki/Web_worker

# Websockets

  • The WebSocket Protocol is an independent TCP-based protocol.
    WebSocket 协议是一个独立的基于 tcp 的协议。
  • WebSocket is designed to be implemented in web browsers and web servers, but it can be used by any client or server application.
    WebSocket 被设计成在 web 浏览器和 web 服务器中实现,但是它可以被任何客户端或服务器应用程序使用。
  • WebSocket is a protocol providing full-duplex communication channels over a single TCP connection.
    WebSocket 是一个在单个 TCP 连接上提供全双工通信通道的协议。
  • Often used for real time data communications from browser to servers.
    通常用于从浏览器到服务器的实时数据通信。
  • https://en.wikipedia.org/wiki/WebSocket
  • https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API
  • https://html.spec.whatwg.org/multipage/comms.html#network
  • https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_client_applications
  • https://javascript.info/websocket
  • https://medium.com/@cn007b/super-simple-php-websocket-example-ea2cd5893575

# Quiz 6

  1. You can supply multiple files in different video formats to the HTML 5 video tag and let the browser use the one that it prefers.

  2. In JSON you can use single quotes to enclose property names and string property values.

  3. Which of the following ES6 features only allows unique values to be included?

    • map
    • set
  4. When using XMLHttpRequest to make an AJAX POST call you pass the request body as a parameter to the open method?

  5. Backticks ` are used to create template strings.

  6. When using XMLHttpRequest to make an AJAX call what is the ready state value when everything is done?

    • 1
    • 2
    • 3
    • 4
    • 5
  7. ES6 arrow functions must have a return statement if you want to return a value when the function is run.

  8. When you call the geolocation getCurrentPosition method it directly returns the gps position as its return value.

  9. Which web storage technology allows you to store strings in a key/value storage that only persists until the user closes their browser?

    • sessionStorage
    • localStorage
    • Web SQL
    • File Access
  10. Which of the following ES6 features allows you to define a function that takes unlimited parameters?

    • spread
    • rest
    • destructuring
    • default parameters