-
Notifications
You must be signed in to change notification settings - Fork 0
/
myPlayer.js
583 lines (448 loc) · 16.8 KB
/
myPlayer.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
;
window.indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;
window.IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction || window.msIDBTransaction;
window.IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange || window.msIDBKeyRange;
;(function(win,doc,$){
'use strict';
if(!window.indexedDB){
alert("什么年代了啊啊啊啊啊啊,还不升级浏览器!");
window.open("http://www.google.cn/intl/zh-CN/chrome/browser/desktop/index.html");
return false;
}
var defaults = {
audio : new Audio,
lrc : null,
canScroll : true,
timeOut : null,
playingId : null,
};
var opt = {
listHeight : 210,
loop : false,
autoplay : false,
listPlay : true,
isDelete : false,
songUrl : "./php/musicPlay.php",
listUrl : "./test.php",
showMsg : function(msg){
if($(".musMsg:last").length){
$(".musMsg:last").prev().hide();
var msgTop =($(".musMsg:last").offset().top -60) < 100 ? $("#player").offset().top-60 : ($(".musMsg:last").offset().top -60);
}else{
var msgTop = $("#player").offset().top-60;
}
var msgStr = "<div class='musMsg' style='position:fixed;left:-400px;top:"+msgTop+"px;height:50px;font: normal normal 16px/16px \"Microsoft YaHei\",Helvetica;padding:17px 20px;color:#fff;background-color:rgba(0,0,0,0.7)'>"+msg+"</div>";
$(doc.body).append(msgStr);
$(".musMsg:last").animate({left:0}, 300, "linear", function(){
var _this = $(this);
setTimeout(function() {
_this.animate({left:-400}, 300, "linear", function(){
_this.remove();
});
}, 2000);
});
},
};
var mPlay = {
init : function(options){
options && $.type(options)=="object" ? $.extend(true, opt, options, defaults) : $.extend(true, opt, defaults);
opt.audio.loop = false;
opt.audio.autoplay = true;
$("#player").length===0 ? mPlay.layout() : mDb.getAll(opt.autoplay);
},
layout : function(){
var playerStr="<div id='player'><div id='mus-info'><div id='bgimg'></div><div id='close' title='隐藏'></div><div id='mus-title' class='mus-info'></div><div id='mus-artist' class='mus-info'></div><div id='mus-time' class='mus-info'></div><div id='lrc'></div></div><div id='list-box'><div id='list-total'>Musics ( <span id='total-num'>0</span> )<span id='list-remove' title='清空列表'></span></div><div id='mus-list'></div><div id='scrollbox'><div id='scrollbar'></div></div></div><ul id='list-bar'><li class='gedan'>Hot</li><li class='gedan'>歌单</li><li class='gedan'>推荐</li></ul><div id='mus-bottom'><div id='timebar'></div><div id='btns'><span id='mode' class='play-mode btn-bottom'></span><span id='show-list' class='btn-bottom' title='播放列表'></span><a href='javascript:;' id='prev' class='mus-btn' title='上一首'></a><a href='javascript:;' id='play' class='mus-btn pause' title='播放/暂停(p)'></a><a href='javascript:;' id='next' class='mus-btn' title='下一首'></a></div></div></div><div id='musicbar'><canvas id='myCanvas' width='48px' height='48px'></canvas></div>";
$(doc.body).append(playerStr);
$("#mus-list").css("max-height", opt.listHeight);
mDb.getAll(opt.autoplay);
mPlay.event();
},
setList : function(data){
var songListStr = "";
if(data[0]){
$.each(data, function(index, tag){
var tagStr = JSON.stringify(tag);
songListStr +="<li class='song-list' songId='"+tag.songId+"'><span class='song-title' title=\""+tag.songTitle+" By "+tag.artist+"\" data='"+tagStr+"'>"+tag.songTitle+"</span><span class='song-remove' title='删除'></span></li>";
});
$("#mus-list").html(songListStr);
$("#list-box").slideDown(100,"swing");
}else{
$("#mus-list").empty();
}
$("#total-num").html($("#mus-list li").length);
},
addSong : function(songObject, isPlay){
var songListStr,
tag = songObject;
var tagStr = JSON.stringify(tag);
songListStr ="<li class='song-list' songId='"+tag.songId+"'><span class='song-title' title=\""+tag.songTitle+" By "+tag.artist+"\" data='"+tagStr+"'>"+tag.songTitle+"</span><span class='song-remove' title='删除'></span></li>";
$("#mus-list").append(songListStr);
$("#total-num").html($("#mus-list li").length);
isPlay ? mPlay.doPlay($("#mus-list li:last-of-type")) : opt.showMsg("歌曲已添加到播放列表");
},
addedPlay : function(songId){
$("#mus-list li").each(function(){
$(this).attr("songId") == songId ? mPlay.doPlay($(this)) : null;
});
},
doPlay : function(ele){
if(ele.length ==0) return false;
var data = $.parseJSON(ele.find("span.song-title").attr("data"));
opt.audio.muted = true;
$("#lrc").empty();
$.post(opt.songUrl, {song:data.songId}, function(res){
if(res.songUrl == "h"){
opt.showMsg("歌曲链接不存在!");
opt.isDelete ? mPlay.playNext() || mDb.deleteOne(ele): mPlay.playNext();
}else{
opt.audio.src = res.songUrl;
opt.audio.muted = false;
opt.lrc = res.lrc;
opt.playingId = data.songId;
opt.audio.onloadedmetadata = function(){
mPlay.audioEvent();
}
}
});
$("#mus-title").html(data.songTitle);
$("#mus-artist").html(data.artist);
$("#mus-time").html("-- / --");
ele.addClass("playing").siblings().removeClass("playing");
$("#bgimg").css("background-image","url("+data.songImg+")").fadeIn();
},
removeSong : function(ele){
ele.remove();
opt.showMsg("歌曲已删除");
$("#mus-list li").length == 0 ? $("#total-num").html(0) : $("#total-num").html($("#mus-list li").length);
},
playNext : function(){
var nextSong = $("#mus-list li.playing").next("li");
nextSong.length > 0 ? mPlay.doPlay(nextSong) : !$("#mus-list li:first-of-type").length || mPlay.doPlay($("#mus-list li:first-of-type"));
},
playPrev : function(){
var prevSong = $("#mus-list li.playing").prev("li");
prevSong.length > 0 ? mPlay.doPlay(prevSong) : !$("#mus-list li:last-of-type").length || mPlay.doPlay($("#mus-list li:last-of-type"));
},
showPlayer : function(show){
if(show){
$("#musicbar").hide();
$("#player").animate({left:0},400,"linear");
}else{
$("#player").animate({left:-400},400,"linear",function(){
$("#musicbar").fadeIn();
});
}
},
toScroll : function(delta){
var musList = $("#mus-list"),
scrollbox = $("#scrollbox"),
scrollbar = $("#scrollbar"),
totalHeight = musList.find("li").length * 20 + 10;
if(totalHeight>opt.listHeight){
scrollbox.height(opt.listHeight);
scrollbar.height(opt.listHeight*opt.listHeight/totalHeight);
scrollbox.fadeIn();
if(opt.canScroll){
opt.canScroll = false;
var scrollbarTop, listScrollTop, scrollbarHeight = scrollbar.height();
scrollbarTop = (scrollbar.position().top+delta)<0 ? 0 : ((scrollbar.position().top+delta)>(opt.listHeight-scrollbarHeight) ? (opt.listHeight-scrollbarHeight) : (scrollbar.position().top+delta));
listScrollTop = (totalHeight-opt.listHeight)*scrollbarTop/(opt.listHeight-scrollbarHeight);
musList.scrollTop(listScrollTop);
scrollbar.animate({top:scrollbarTop},50,"linear",function(){
opt.canScroll = true;
});
}
}else{
scrollbox.fadeOut();
}
},
drawProcess : function(barWidth, text){
var c=document.getElementById("myCanvas");
var context=c.getContext("2d");
context.clearRect(0, 0, 48, 48);
// ***开始画一个灰色的圆
context.beginPath();
// 坐标移动到圆心
context.moveTo(24, 24);
// 画圆,圆心是24,24,半径24,从角度0开始,画到2PI结束,最后一个参数是方向顺时针还是逆时针
context.arc(24, 24, 24, 0, Math.PI * 2, false);
context.closePath();
// 填充颜色
context.fillStyle = '#ddd';
context.fill();
// ***灰色的圆画完
// 画进度
context.beginPath();
// 画扇形的时候这步很重要,画笔不在圆心画出来的不是扇形
context.moveTo(24, 24);
// 跟上面的圆唯一的区别在这里,不画满圆,画个扇形
context.arc(24, 24, 24, 0, barWidth, false);
context.closePath();
context.fillStyle = '#999';
context.fill();
// 画内部空白
context.beginPath();
context.moveTo(24, 24);
context.arc(24, 24, 21, 0, Math.PI * 2, true);
context.closePath();
context.fillStyle = 'rgba(255,255,255,1)';
context.fill();
context.font = "bold 9pt Arial";
context.fillStyle = '#999';
context.textAlign = 'center';
context.textBaseline = 'middle';
context.moveTo(24, 25);
context.fillText(text, 25, 25);
},
secondsToMinutes : function(seconds){
var MM = Math.floor(seconds/60),
SS = Math.floor(seconds%60);
MM<10 ? (MM="0"+MM) : MM;
SS<10 ? (SS="0"+SS) : SS;
var time = MM+":"+SS;
return time;
},
event : function(){
$(".gedan").click(function(){
var data = $(this).text();
$.post(opt.listUrl, data, function(res){
mDb.addTo(res, opt.listPlay);
$("#list-box").slideDown(100,"swing");
});
});
$("#mus-list").on("click", ".song-title", function(){
mPlay.doPlay($(this).parent());
});
$("#mus-list").on("click", ".song-remove",function(){
if($(this).parent().hasClass("playing")) mPlay.playNext();
mDb.deleteOne($(this).parent());
});
$("#next").click(function(){
mPlay.playNext();
});
$("#prev").click(function(){
mPlay.playPrev();
});
$("#play").click(function(){
if($("#mus-list li.playing").length == 0){
mPlay.playNext();
}else{
opt.audio.paused ? opt.audio.play() : opt.showMsg("已暂停:"+$("#mus-title").text()) || opt.audio.pause();
}
});
$("#mode").click(function(){
opt.loop = !opt.loop;
opt.loop ? opt.showMsg("单曲循环") || $(this).removeClass("play-mode").addClass("play-mode-loop") : opt.showMsg("列表循环") || $(this).removeClass("play-mode-loop").addClass("play-mode");
});
$("#show-list").click(function(){
$("#list-box").slideToggle(100,"swing");
});
$("#musicbar").click(function(){
mPlay.showPlayer(true);
});
$("#close").click(function(){
mPlay.showPlayer(false);
});
$("#list-remove").click(function(){
$("#list-box").slideUp(100,"swing");
mDb.deleteAll();
opt.showMsg("播放列表已清空!");
});
$("#mus-list").on("mouseenter", function(){
mPlay.toScroll( 0 );
}).on("mousewheel DOMMouseScroll", function(e){
e.preventDefault();
e.stopPropagation();
var delta = -e.originalEvent.wheelDelta/12 || e.originalEvent.detail/3*20;
mPlay.toScroll(delta);
}).on("mouseleave", function(){
$("#scrollbox").fadeOut();
});
},
audioEvent : function(){
var timeBar = $("#timebar"),
musTime = $("#mus-time"),
musBar = $("#musicbar"),
musLrc = $("#lrc");
var duration = opt.audio.duration,
durationTime = mPlay.secondsToMinutes(duration);
opt.audio.onended = function(){
opt.loop ? !$(".playing").length || mPlay.doPlay($(".playing")) : mPlay.playNext();
};
opt.audio.onpause = function(){
$("#play").removeClass("play").addClass("pause");
};
opt.audio.onplay = function(){
$("#play").removeClass("pause").addClass("play");
opt.showMsg("正在播放:"+$("#mus-title").text());
};
opt.audio.onwaiting = function(){
opt.showMsg("正在缓冲!");
};
opt.audio.onerror = function(){
mPlay.playNext();
opt.showMsg("资源加载失败!");
};
opt.audio.ontimeupdate = function(){
var currentTime = opt.audio.currentTime,
playTime = mPlay.secondsToMinutes(currentTime);
var bar = 2*Math.PI*currentTime/duration,
barWidth = 100*Math.floor(currentTime)/Math.floor(duration) +"%";
timeBar.width(barWidth);
mPlay.drawProcess(bar, playTime);
musTime.html(playTime+" / "+durationTime);
if(opt.lrc !==0){
$.each(opt.lrc, function(index,value){
if(index>Math.floor(currentTime*1000-300) && index<Math.floor(currentTime*1000+300)){
musLrc.html(value);
delete opt.lrc[index];
return false;
}
});
}else{
musLrc.html("No Lyrics");
}
}
},
};
var mDb = {
version: 1, // important: only use whole numbers!
objectStoreName: 'mPlay',
objectIndex: 'songId',
instance: {},
upgrade: function (e) {
var _mDb = e.target.result,
names = _mDb.objectStoreNames,
name = mDb.objectStoreName,
storeIndex = mDb.objectIndex;
if (!names.contains(name)) {
var objectStore = _mDb.createObjectStore( name,{ keyPath: 'id', autoIncrement: true, unique: true});
objectStore.createIndex(storeIndex,storeIndex,{unique:true});
}
},
errorHandler: function (error) {
console.log('error: ' + error.target.error);
//debugger;
},
open: function (callback) {
var request = win.indexedDB.open(mDb.objectStoreName, mDb.version);
request.onerror = mDb.errorHandler;
request.onupgradeneeded = mDb.upgrade;
request.onsuccess = function (e) {
mDb.instance = request.result;
mDb.instance.onerror = mDb.errorHandler;
callback();
};
},
getObjectStore: function (mode) {
mode = mode || 'readonly';
var txn, store,
txn = mDb.instance.transaction([mDb.objectStoreName], mode),
store = txn.objectStore(mDb.objectStoreName);
return store;
},
addTo : function(musData, isPlay){
var isPlay = isPlay || false;
mDb.open(function () {
var txn = mDb.instance.transaction([mDb.objectStoreName], 'readwrite'),
store = txn.objectStore(mDb.objectStoreName);
var songObject,data = musData;
if(!data.songList){
if(data.songId && $.type(data.songId)=="number"){
var index = store.index("songId").get(data.songId);
index.onsuccess = function(e){
if (!e.target.result) {
store.put(data).onsuccess = function(e){
songObject = data;
songObject.id = e.target.result;
};
}
}
txn.oncomplete = function(e){
if(songObject){
mPlay.addSong(songObject, isPlay);
}else if(isPlay){
opt.playingId != data.songId ? mPlay.addedPlay(data.songId) : opt.showMsg("歌曲已添加到播放列表");
}else{
opt.showMsg("歌曲已添加到播放列表");
}
}
}else{
opt.showMsg("歌曲数据错误");
}
}else{
store.clear().onsuccess = function(){
$.each(data.songList, function(index, value){
if(value.songId && $.type(value.songId)=="number"){
store.put(value);
txn.oncomplete = function(e){
mDb.getAll(isPlay);
opt.showMsg("歌曲已添加到播放列表");
}
}else{
opt.showMsg("第"+(index+1)+" 首歌曲数据错误");
}
});
};
}
});
},
getAll: function (isPlay) {
var isPlay = isPlay || false;
mDb.open(function () {
var store = mDb.getObjectStore(),
cursor = store.openCursor(),
data = [];
cursor.onsuccess = function (e) {
var result = e.target.result;
if (result && result !== null) {
data.push(result.value);
result.continue();
} else {
mPlay.setList(data);
isPlay ? mPlay.playNext() : null;
}
};
});
},
deleteOne: function (ele) {
var id = parseInt($.parseJSON(ele.find("span.song-title").attr("data")).id);
mDb.open(function () {
var mode = 'readwrite', store, request;
store = mDb.getObjectStore(mode);
request = store.delete(id);
request.onsuccess = mPlay.removeSong(ele);
});
},
deleteAll: function () {
mDb.open(function () {
var mode, store, request;
mode = 'readwrite';
store = mDb.getObjectStore(mode);
request = store.clear();
request.onsuccess = mPlay.setList([]);
});
}
};
win.pl = win.pl || {};
win.pl.init = mPlay.init;
win.pl.addTo = mDb.addTo;
$(function(){
win.pl.init({
showMsg : function(msg){
$(".musMsg").length ? $(".musMsg").hide() : null;
var msgBottom = $("#player").height() + 10;
var msgStr = "<div class='musMsg' style='position:fixed;left:-400px;bottom:"+msgBottom+"px;height:50px;font: normal normal 16px/16px \"Microsoft YaHei\",Helvetica;padding:17px 20px;color:#fff;background-color:rgba(0,0,0,0.7)'>"+msg+"</div>";
$(doc.body).append(msgStr);
$(".musMsg:last").animate({left:0}, 300, "linear", function(){
var _this = $(this);
setTimeout(function() {
_this.animate({left:-400}, 300, "linear", function(){
_this.remove();
});
}, 2000);
});
},
});
});
})(window,document,jQuery);