HTML5 API - Audio



총 2회에 걸쳐 HTML5 API의 Audio 객체와 Video 객체에 대해 알아 보도록 하겠습니다.


또한, 글로 기능을 나열하기 보다는 소스 위주의 설명으로 진행하도록 하겠습니다.



아래는 HTML5 API가 지원하고 있는 Audio 객체의 모든 기능을 모듈화 시킨 코드이며, 현재 명세에 있는 모든 기능을 포함합니다.


  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3. <head>
  4.     <title>Audio</title>
  5. </head>
  6. <body>
  7. <script type="text/javascript">
  8. //<![CDATA[
  9.  
  10.     var Audio = (function (win, doc) {
  11.  
  12.         return function (opt) {
  13.  
  14.             function init() {
  15.  
  16.                 this.options = {
  17.                     player: null,
  18.  
  19.                     wrap: null,
  20.  
  21.                     id: '',
  22.                     src: '',
  23.                     autoplay: false,
  24.                     controls: false,
  25.                     loop: false,
  26.                     isloaded: false,
  27.                     onload: function () { ; },
  28.                     onplay: function () { ; },
  29.                     onprogress: function () { ; },
  30.                     ontimeupdate: function () { ; },
  31.                     onended: function () { ; },
  32.                     onerror: function () { ; }
  33.                 };
  34.  
  35.                 extend.call(this.options, opt);
  36.  
  37.                 // audio load
  38.                 load.call(this.options);
  39.  
  40.                 return this;
  41.             }
  42.  
  43.             Audio.fn = init.prototype = {
  44.                 play: play,
  45.                 stop: stop,
  46.                 isEnded: isEnded,
  47.                 getTimeout: getTimeout,
  48.                 getStartTime: getStartTime,
  49.                 getSrc: getSrc,
  50.                 isBuffering: isBuffering,
  51.                 getCurrentTimeout: getCurrentTimeout,
  52.                 setVolume: setVolume,
  53.                 setMuted: setMuted
  54.  
  55.             }
  56.  
  57.             return new init();
  58.         };
  59.  
  60.         // audio 객체를 생성한다.
  61.         function createElement() {
  62.  
  63.             this.player = document.createElement('audio');
  64.  
  65.             this.player.id = this.id;
  66.             this.player.src = this.src;
  67.             this.player.autoplay = this.autoplay;
  68.             this.player.controls = this.controls;
  69.             this.player.loop = this.loop;
  70.  
  71.             // 미디어클립을 재생할 준비가 완료 시 이벤트 핸들러
  72.             bind(this.player, 'canplay', function () {
  73.  
  74.                 that.onload.call(null);
  75.                 this.isloaded = true;
  76.             });
  77.  
  78.             var that = this;
  79.  
  80.             // 미디어클립 재생 클릭 시 이벤트 핸들러
  81.             bind(this.player, 'play', function () { that.onplay.call(null); });
  82.             // 브라우저가 미디어클립 데이터를 가져오는 프로세스에 있을 시 이벤트 핸들러
  83.             bind(this.player, 'progress', function () { that.onprogress.call(null); });
  84.             // 미디어 클립 재생 시 지속적으로 발생(재생 위치가 변경되었을때)
  85.             bind(this.player, 'timeupdate', function () { that.ontimeupdate.call(null); });
  86.             // 미디어 클립 종료 시 이벤트 핸들러
  87.             bind(this.player, 'ended', function () { that.onended.call(null); });
  88.             // 미디어 클립 로드 오류 시 이벤트 핸들러
  89.             bind(this.player, 'error', function () { that.onerror.call(null); });
  90.  
  91.             return this.player;
  92.         };
  93.  
  94.         // audio 객체를 로드합니다.
  95.         function load() {
  96.             var elem = createElement.call(this);
  97.  
  98.             if (elem.load) (this.wrap || document.body).appendChild(elem);
  99.             else alert('Audio 객체를 지원하지 않는 브라우저 입니다.');
  100.         };
  101.  
  102.         // 미디어클립을 재생합니다.
  103.         function play() {
  104.  
  105.             this.options.player.play();
  106.  
  107.             return this;
  108.         };
  109.  
  110.         // 미디어클립 재생을 중지합니다.
  111.         function stop() {
  112.  
  113.             !this.options.player.paused && this.options.player.pause();
  114.             return this;
  115.         }
  116.  
  117.         // 미디어클립 재생 여부를 반환
  118.         function isEnded() {
  119.             return this.options.player.ended;
  120.         };
  121.  
  122.  
  123.         // 미디어클립의 총 재생시간을 반환
  124.         function getTimeout(type) {
  125.  
  126.             type = type || 'hours';
  127.  
  128.             return {
  129.                 'second': this.options.player.startTime,
  130.                 'hours': getDateSecondToHours(this.options.player.duration)
  131.             }[type];
  132.         };
  133.  
  134.         // 미디어클립의 현재 재생시간을 반환
  135.         function getCurrentTimeout(type) {
  136.  
  137.             type = type || 'hours';
  138.  
  139.             return {
  140.                 'second': this.options.player.currentTime,
  141.                 'hours': getDateSecondToHours(this.options.player.currentTime)
  142.             }[type];
  143.         };
  144.  
  145.         // 미디어 클립의 현재 재생 시간을 반환
  146.         // 0.0(min) ~ 1(max) 할당한다.
  147.         function setVolume(num) {
  148.  
  149.             num = num || 0;
  150.  
  151.             this.options.player.volume = num / 10;
  152.  
  153.             return this;
  154.         };
  155.  
  156.         // 음소거 여부를 설정한다.
  157.         function setMuted(b) {
  158.  
  159.             b = b || false;
  160.  
  161.             this.options.player.muted = b;
  162.  
  163.             return this;
  164.         };
  165.  
  166.         // 미디어 클립이 재생을 시작할 수 있는 가능한 가장 빠른 시간을 반환합니다.
  167.         // 미디어 클립이 스트리밍되거나, 버퍼링되지 않으면 0을 반환합니다.
  168.         function getStartTime(type) {
  169.  
  170.             return this.options.player.startTime;
  171.         };
  172.  
  173.         // 현재 버퍼링 상태 여부를 반환
  174.         function isBuffering() {
  175.             return this.options.player.startTime !== 0;
  176.         };
  177.  
  178.         // 현재 재생중인 파일명을 반환합니다.
  179.         function getSrc() {
  180.             return this.options.player.currentSrc;
  181.         };
  182.  
  183.  
  184.         function getDateSecondToHours(i) {
  185.  
  186.             i = i || 0;
  187.  
  188.             var h = parseInt(((i / 3600) % 24), 10)
  189.               , m = parseInt(((i / 60) % 60), 10)
  190.               , s = parseInt(((i / 1) % 60), 10);
  191.  
  192.             h = h < 10 ? '0' + h : h;
  193.             m = m < 10 ? '0' + m : m;
  194.             s = s < 10 ? '0' + s : s;
  195.  
  196.             return h + ':' + m + ':' + s;
  197.         };
  198.  
  199.         // 객체 상속 함수
  200.         function extend() {
  201.  
  202.             var target = this
  203.           , opts = []
  204.           , src = null
  205.           , copy = null;
  206.  
  207.             for (var i = 0, length = arguments.length; i < length; i++) {
  208.  
  209.                 opts = arguments[i];
  210.  
  211.                 for (var n in opts) {
  212.                     src = target[n];
  213.                     copy = opts[n];
  214.  
  215.                     if (src === copy) continue;
  216.                     if (copy) target[n] = copy;
  217.                 }
  218.             }
  219.         };
  220.  
  221.  
  222.     })(window, document);
  223.  
  224.  
  225.     bind(window, 'load', function () {
  226.  
  227.         p1 = Audio({
  228.             id: 'audio_test1',
  229.             src: 'http://m.fpscamp.com/free.mp3',
  230.             autoplay: false,
  231.             controls: true,
  232.             loop: false,
  233.             onload: function () {
  234.             },
  235.             onplay: function () {
  236.             },
  237.             onprogress: function () {
  238.             },
  239.             ontimeupdate: function () {
  240.             },
  241.             onended: function () {
  242.                 alert('onended');
  243.             },
  244.             onerror: function () {
  245.                 alert(this === window);
  246.             }
  247.         });
  248.     });
  249.  
  250.     // 이벤트 할당
  251.     function bind(elem, type, handler, capture) {
  252.         type = typeof type === 'string' && type || '';
  253.         handler = handler || function () { ; };
  254.  
  255.         if (elem.addEventListener) {
  256.             elem.addEventListener(type, handler, capture);
  257.         }
  258.         else if (elem.attachEvent) {
  259.             elem.attachEvent('on' + type, handler);
  260.         }
  261.  
  262.         return elem;
  263.     };
  264.  
  265. //]]>
  266. </script>
  267. <input id="" type="button" value="play" onclick="p1.play()" />
  268. <input id="" type="button" value="stop" onclick="p1.stop()" />
  269. <input id="" type="button" value="isEnded" onclick="alert(p1.isEnded())" />
  270. <input id="" type="button" value="getTimeout" onclick="alert(p1.getTimeout())" />
  271. <input id="" type="button" value="getStartTime" onclick="alert(p1.getStartTime())" />
  272. <input id="" type="button" value="getSrc" onclick="alert(p1.getSrc())" />
  273. <input id="" type="button" value="isBuffering" onclick="alert(p1.isBuffering())" />
  274. <input id="" type="button" value="getCurrentTimeout" onclick="alert(p1.getCurrentTimeout())" />
  275. <input id="" type="button" value="setVolume" onclick="p1.setVolume(5)" />
  276. <input id="" type="button" value="setMuted" onclick="p1.setMuted(true)" />
  277. </body>
  278. </html>



실행 페이지:


Audio 객체 브라우저 지원 상황:




참고사이트:


레퍼런스:

http://www.w3schools.com/html5/tag_audio.asp


브라우저 지원 여부

 http://caniuse.com/


@박종명님의 블로그


http://m.mkexdev.net/63