iT邦幫忙

2018 iT 邦幫忙鐵人賽
0
Modern Web

30天學習30套前端技術(2018年)系列 第 39

[十分鐘學習] howler.js - 音源播放函式庫

example1

howler.js是針對時下網站的一套音源播放函式庫,預設為Web Audio API和HTML5 Audio,可以透過JavaScript播放聲音變得更簡單,並且跨平台

GitHub Star: 9,300
Javascripting Overall: 86%
瀏覽器: ChromeFirefoxIE9+
RWD: 不支援(可運作)
License: MIT


《安裝》

  • CDN

      <!-- howler.js v2.0.8 -->
      <script src="https://cdnjs.cloudflare.com/ajax/libs/howler/2.0.8/howler.min.js"></script>
    
  • npm

      $ npm install howler
    
  • Bower

      $ bower install howler
    
  • Yarn

      $ yarn add howler
    

《範例》

  • 包含播放、暫停和停止音樂的播放器

      <em id="state"></em>
      <hr />
      <button onclick="javascript:play();">播放</button>
      <button onclick="javascript:stop();">停止</button>
      <button onclick="javascript:pause();">暫停</button>
      <script>
      	var sound = new Howl({
      		// 參數設定[註1]
      			src: [ "https://www.var.tw/it2018/day39.mp3" ],
      			autoplay: false, // 自動播放
      			loop: false, // 無限循環
      			volume: 0.5, // 音量ntById( "state" ).innerText = "結束";
      			onload: function() {
      				// 載入後執行
      				document.getElementById( "state" ).innerText = "載入完成";
      			},
      			onplay: function() {
      				// 播放後執行
      				document.getElementById( "state" ).innerText = "播放中";
      			},
      			onpause: function() {
      				// 暫停後執行
      				document.getElementById( "state" ).innerText = "暫停";
      			},
      			onstop: function() {
      				// 停止後執行
      				document.getElementById( "state" ).innerText = "停止";
      			},
      			onend: function() {
      				// 結束後執行
      				document.getElementById( "state" ).innerText = "結束";
      			}
      		});
    
      	function play() {
      		sound.play(); // 播放
      	}
      	function stop() {
      		sound.stop(); // 停止
      	}
      	function pause() {
      		sound.pause(); // 暫停
      	}
      </script>
    

    [註1]

    參數 描述

    autoplay|自動播放
    loop|無限循環
    volume|音量

    函式列表

    函式 描述

    play()|播放
    stop()|停止
    pause()|暫停


《延伸》

  1. howler.js - JavaScript audio library for the modern web
  2. goldfire/howler.js: Javascript audio library for the modern web.

上一篇
[十分鐘學習] clipboard.js - 複製/貼上
下一篇
[十分鐘學習] p5.js - 繪畫套件
系列文
30天學習30套前端技術(2018年)61
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言