audiojs 音频插件使用教程

audiojs 音频插件使用教程

github地址

https://kolber.github.io/audiojs/

依赖文件

<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.js"></script>
<script src="./audiojs/audio.min.js"></script>
<link rel="stylesheet" href="./includes/index.css" media="screen">

html代码块

<audio preload></audio>
<ol>
    <li><a href="#" data-src="2.mp3">dead wrong intro</a></li>
    <li><a href="#" data-src="2.mp3">juicy-r</a></li>
</ol>

js代码块

插件初始化

// 初始化插件
var a = audiojs.createAll({
    trackEnded: function() {
        var next = $('ol li.playing').next();
        if (!next.length) next = $('ol li').first();
        next.addClass('playing').siblings().removeClass('playing');
        audio.load($('a', next).attr('data-src'));
        audio.play();
    }
});

加载第一个音频文件

// 加载第一个文件
var audio = a[0];
first = $('ol a').attr('data-src');
$('ol li').first().addClass('playing');
audio.load(first);

点击列表切换播放

// 点击列表切换播放
$('ol li').click(function(e) {
    e.preventDefault();
    $(this).addClass('playing').siblings().removeClass('playing');
    audio.load($('a', this).attr('data-src'));
    audio.play();
});

键盘控制播放

// 键盘控制播放
$(document).keydown(function(e) {
    var unicode = e.charCode ? e.charCode : e.keyCode;
    // ->键盘切换下一首
    if (unicode == 39) {
        var next = $('li.playing').next();
        if (!next.length) next = $('ol li').first();
        next.click();
        // <-切换上一首
    } else if (unicode == 37) {
        var prev = $('li.playing').prev();
        if (!prev.length) prev = $('ol li').last();
        prev.click();
        // 空格暂停
    } else if (unicode == 32) {
        audio.playPause();
    }
})
原文地址:https://www.cnblogs.com/yz-blog/p/7809316.html