您的位置:首页 > Web前端 > HTML5

HTML5用audio标签做一个最简单的音频播放器

2015-10-27 21:30 696 查看
在做系统的时候,要求做一个音频播放器,就在网上查找了一些资料,发现这样的资料还是很千篇一律的,EasyUI框架并没有给我们一个音频播放器的功能,在bootstrap上有,但是也是结合html5来写的,因此,我们在这里就用纯的html5血一个音频播放器,如何播放本地的音频。

首先,大家在myeclipse上建立一个自己的web项目:



其实,这里的代码都不难,主要的问题出在,自己没有弄明白jsp界面上引用的js和css的文件目录,我将我们用到的音频文件放在了avatar文件下面,因为这里用到的“http://file.dengo.org/music/cyx_ds.mp3”,一直播放不了,因此我就用本地的音频试试,就还好, 基本代码:

testEar.jsp:

<span style="font-size:18px;"><%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    
    <title>最简单的音频播放器</title>
    
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <link rel="stylesheet" type="text/css" href="/TestEar/testEar/css/style.css">
  </head>
 
  <body>
    <div class="music_wrap">

        <div class="control">
            <div class="option">
                <div class="time">-00:00</div>
                <div class="volume" title="音量">
                    <p></p>
                </div>
                <div class="volume_wrap hidden">
                    <div class="volume_bar">
                        <div class="volume_now"></div>
                    </div>
                </div>

            </div>
 
            <div class="progress_bar" id="bar">
                <div class="progress"></div>
                <div class="buffer"></div>
            </div>
 
            <div class="action_button">
                <div class="prev" title="上一首"></div>
                <div class="play" title="播放" id="play"></div>
                <div class="pause hidden" title="暂停"></div>
                <div class="next" title="下一首"></div>
            </div>
        </div>
 
        <audio id="audio">
            <p>您的浏览器不支持HTML5播放器呢!赶紧换一个最新的呗^_^.</p>
        </audio>
    </div>

    <script type="text/javascript" src="/TestEar/testEar/js/list.js"></script>
    <script type="text/javascript" src="/TestEar/testEar/js/index.js"></script>

  </body>
</html>
</span>


style.css文件:

<span style="font-size:18px;">@charset "UTF-8";
/*
* @author		qmx
* @email
* @link
* @project		HTML5_Player
* @description
*/
/* ----- reset ----- */
body,div,dl,dt,dd,ul,ol,li,h1,h2,h3,h4,h5,h6,pre,form,fieldset,input,textarea,p,blockquote,th,td{margin:0;padding:0}
h1,h2,h3,h4,h5,h6{font-size:100%;font-weight:normal;}
button, input, select, textarea {font-size: 100%;}
body,button,input,select,textarea{font: 12px/1.5 'Microsoft YaHei',Arial,"\5b8b\4f53",Tahoma,sans-serif;}
a,a:link,a:visited,a:focus,a:hover,a:active{text-decoration:none;}
fieldset,img{border:0}
ol,ul{list-style:none}
address,caption,cite,code,dfn,em,th,var{font-style:normal; font-weight:normal}
caption,th{text-align:left}
abbr,acronym{border:0}
table {border-collapse:collapse; border-spacing:0;}/* tables still need 'cellspacing="0"' in the markup */
img{ -ms-interpolation-mode:bicubic; }/*for ie7*/
:focus {outline-color: -moz-use-text-color;outline-style: none;outline-width: 0;}
/* ----- reset end ------ */
/* ----- css ----- */
@font-face {
font-family: 'icon';
src:url('../fonts/icon.eot?');
src:url('../fonts/icon.eot?#iefix') format('embedded-opentype'),
url('../fonts/icon.woff?') format('woff'),
url('../fonts/icon.ttf?') format('truetype'),
url('../fonts/icon.svg?#icon') format('svg');
font-weight: normal;
font-style: normal;
}
body{
background-color: #F2F2F0;
}
.music_wrap{
width: 355px;
height: 50px;
margin: 50px auto;
box-shadow: 0px 0px 20px #D8D8D8;
border-radius: 10px;
}
.control{
height: 160px;
margin-top: 10px;
position: relative;
}
/*播放模式*/
.option{
height: 22px;
font-size: 13px;
color: #A1A1A1;
}
.time{
float: left;
margin-left: 16px;
line-height: 22px;
}
.volume{
color: #A0A0A0;
font-family: 'icon';
font-size: 16px;
float: right;
margin-right: 10px;
cursor: pointer;
}
.list{
font-size: 20px;
line-height: 24px;
color: #4BA3DC;
}
/*音量调节*/
.volume{
margin-right: 16px;
color: #4BA3DC;
}
.volume_wrap{
width: 15px;
height: 90px;
position: absolute;
right: 18px;
top: -90px;
z-index: 99;
cursor: pointer;
border-radius: 9px;
background-color: #fff;
box-shadow: 0 0 10px #D9D9D9;
}
.volume_bar{
width: 9px;
height: 80px;
background-color: #D5D5D5;
position: absolute;
border-radius: 9px;
left: 3px;
top: 5px;
}
.volume_now{
width: 9px;
height: 64px;
background-color: #4BA3DC;
position: absolute;
bottom: 0;
border-radius: 9px;
}
/*播放进度条*/
.progress_bar{
width: 324px;
height: 10px;
background-color: #E5E5E3;
border-radius: 5px;
margin: 3px auto 0;
position: relative;
cursor: pointer;
}
.progress{
width: 0px;
height: 10px;
background-color: #4BA3DC;
border-radius: 5px;
position: absolute;
z-index: 11;
}
.buffer{
width: 0px;
height: 10px;
background-color: #D5D5D5;
border-radius: 5px;
position: absolute;
z-index: 1;
}
.hidden{
display: none;
}
</span>


list.js文件:

<span style="font-size:18px;">/*
* @author		qmx
* @email		i@dengo.org
* @link
* @project		playList
* @description	保存歌曲信息
*/
var playList = [
{
'musicURL' : '/TestEar/testEar/avatar/1.mp3',
}
];
</span>


这里写我们音频文件的地址。
 

音频播放文件index.js:

<span style="font-size:18px;">/*
* @author		qmx
* @email
* @link
* @project		HTML5_Player
* @description	播放js
*/
window.onload=function(){
function $(ele){
return document.querySelector(ele);
}
//=========================================初始化所有数据
var audio = $('#audio');
var musicMode = 'list';
var musicIndex = 1;
var bufferTimer = null;
var volumeTimer = null;
//===========================================
//小喇叭和调整音量的大小
$('.volume').onmouseover=$('.volume_wrap').onmouseover=function(){
clearTimeout(volumeTimer);
removeClass($('.volume_wrap'),'hidden')
};
$('.volume').onmouseout=$('.volume_wrap').onmouseout=function(){
volumeTimer = setTimeout(function(){
addClass($('.volume_wrap'),'hidden');
},300);
};
$('.volume_bar').onclick=function(ev){
adjustVolume(this,ev);
};
$('.volume').onclick=function(){
if (audio.muted == false) {
this.style.color = '#A1A1A1';
audio.muted = true;
}
else if (audio.muted == true) {
this.style.color = '#E74D3C';
audio.muted = false;
};
};
//==============================================初始化的时候,音频文件
initPlayer(musicIndex-1);
audio.volume = 0.8;
audio.addEventListener('canplay',bufferBar,false);
function initPlayer(index){
//播放器的播放文件索引号
audio.setAttribute('src',playList[index].musicURL);
$('.progress').style.width =   0 +'px';
//进度条初始化
audio.removeEventListener('canplay',bufferBar,false);
clearInterval(bufferTimer);
$('.buffer').style.width = 0 +'px';
//		toPlay('play');
audio.play();
//隐藏所有按钮
addClass($('.prev'),'hidden');
addClass($('.play'),'hidden');
addClass($('.next'),'hidden');
addClass($('.pause'),'hidden');
}
//=============================================更新时间
audio.addEventListener('timeupdate',function(){
if (!isNaN(audio.duration)) {

var surplus = audio.duration-audio.currentTime;
var surplusMin = parseInt(surplus/60);
var surplusSecond = parseInt(surplus%60);
if (surplusSecond < 10 ) {
surplusSecond = '0'+surplusSecond;
};
$('.time').innerHTML = "-" + surplusMin + ":" +surplusSecond;
//进度条的进行总时间
var progressValue = audio.currentTime/audio.duration*324;
$('.progress').style.width = parseInt(progressValue) + 'px';
};
},false);
//==============================================进度条
function bufferBar(){
bufferTimer = setInterval(function(){
var bufferIndex = audio.buffered.length;
if (bufferIndex > 0 && audio.buffered != undefined) {
var bufferValue = audio.buffered.end(bufferIndex-1)/audio.duration*324;
$('.buffer').style.width = parseInt(bufferValue)+'px';
if (Math.abs(audio.duration - audio.buffered.end(bufferIndex-1)) <1) {
$('.buffer').style.width = 324+'px';
clearInterval(bufferTimer);
};
};
},1000);
}
//===============================================调整音量
function adjustVolume(dom,ev){
var event = window.event || ev;
var volumeY = dom.getBoundingClientRect().bottom - event.clientY;
audio.volume = (volumeY/80).toFixed(2);
$('.volume_now').style.height = volumeY + 'px';
};
//=============================================
function hasClass(dom,className){
var classNum = dom.className.split(" "),
hasClass;
for (var i = 0; i < classNum.length; i++) {
if (classNum[i] == className) {
hasClass = true;
break;
}
else{
hasClass = false;
};
};
return hasClass;
}
function addClass(dom,className){
if (!hasClass(dom,className)) {
dom.className += " " + className;
};
}
function removeClass(dom,className){
if (hasClass(dom,className)) {
var classNum = dom.className.split(" ");
for (var i = 0; i < classNum.length; i++) {
if (classNum[i] == className) {
classNum.splice(i,1);
dom.className = classNum.join(" ");
break;
};
};
};
}
function replaceClass(dom,className,replaceClass){
if (hasClass(dom,className)) {
var classNum = dom.className.split(" ");
for (var i = 0; i < classNum.length; i++) {
if (classNum[i] == className) {
classNum.splice(i,1,replaceClass);
dom.className = className.join(" ");
break;
};
};
};
}
}
</span>


将这些文件放入到对应的文件家中,最简单的音频播放器就做好了。



我们的运行图:



仅仅是最一个英语测试的音频文件,Demo的下载

也有按照网上的播放器中的一个比较高级一点的:


  

这个Demo下载的源码:Demo下载
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息