1. 程式人生 > >Jplayer歌詞同步顯示外掛(在以前別人基礎上修改)

Jplayer歌詞同步顯示外掛(在以前別人基礎上修改)

1、該外掛是一個jquery的編寫的跟jplayer實現歌詞同步的外掛,最終效果如圖:


2、首先引入jplayer的相關的js庫和樣式檔案。

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link href="skin/pink.flag/jplayer.pink.flag.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="js/jquery-1.8.2.min.js"></script>
<script type="text/javascript" src="js/jquery.jplayer.min.js"></script>
<script type="text/javascript" src="js/jquery.jplayer.lyric.js"></script>

3、把我修改的jquery的js檔案貼出來,以備以後不能下載的朋友參考實現:

/*****
*原作mp3player.duapp.com
*修改 :王坤
*QQ群:151013733
*修改內容說明:在原有基礎上,需要使用start方法才能載入歌詞,改進之後,在載入jplayer之前呼叫,顯示歌詞
*/
(function($){
	$.lrc = {
		handle: null, /* 定時執行控制代碼 */
		list: [], /* lrc歌詞及時間軸陣列 */
		regex: /^[^\[]*((?:\s*\[\d+\:\d+(?:\.\d+)?\])+)([\s\S]*)$/, /* 提取歌詞內容行 */
		regex_time: /\[(\d+)\:((?:\d+)(?:\.\d+)?)\]/g, /* 提取歌詞時間軸 */
		regex_trim: /^\s+|\s+$/, /* 過濾兩邊空格 */
		callback: null, /* 定時獲取歌曲執行時間回撥函式 */
		interval: 0.3, /* 定時重新整理時間,單位:秒 */
		format: '<li>{html}</li>', /* 模板 */
		prefixid: 'lrc', /* 容器ID */
		hoverClass: 'hover', /* 選中節點的className */
		hoverTop: 100, /* 當前歌詞距離父節點的高度 */
		duration: 0, /* 歌曲回撥函式設定的進度時間 */
		__duration: -1, /* 當前歌曲進度時間 */
		hasLrc:0,/**記錄是否有歌詞標記**/
		//初始化歌詞 
		init: function(txt){
		if(typeof(txt) != 'string' || txt.length < 1) return;
			/* 停止前面執行的歌曲 */
			this.stop();
			var item = null, item_time = null, html = '';
			/* 分析歌詞的時間軸和內容 */
			//先按行拆分歌詞
			txt = txt.split("\n");
			//對拆分的每行進行提取時間和歌詞內容
			for(var i = 0; i < txt.length; i++) {
				//獲取一行並去掉兩端的空格 [00:11.38]如果你眼神能夠為我片刻的降臨
				item = txt[i].replace(this.regex_trim, '');
				//然後取出歌詞資訊
				if(item.length < 1 || !(item = this.regex.exec(item))) continue;
				while(item_time = this.regex_time.exec(item[1])) {
					this.list.push([parseFloat(item_time[1])*60+parseFloat(item_time[2]), item[2]]);
				}
				this.regex_time.lastIndex = 0;
			}
			/* 有效歌詞 */
			if(this.list.length > 0) {
				this.hasLrc =1;
				/* 對時間軸排序 */
				this.list.sort(function(a,b){ return a[0]-b[0]; });
				if(this.list[0][0] >= 0.1) this.list.unshift([this.list[0][0]-0.1, '']);
				this.list.push([this.list[this.list.length-1][0]+1, '']);
				for(var i = 0; i < this.list.length; i++)
					html += this.format.replace(/\{html\}/gi, this.list[i][1]);
				/* 賦值到指定容器 */
				$('#'+this.prefixid+'_list').html(html).animate({ marginTop: 0 }, 100).show();
				/* 隱藏沒有歌詞的層 */
				$('#'+this.prefixid+'_nofound').hide();
				/* 定時呼叫回撥函式,監聽歌曲進度 */
				//this.handle = setInterval('$.lrc.jump($.lrc.callback());', this.interval*1000);
			}else{ /* 沒有歌詞 */
				this.hasLrc =0;
				$('#'+this.prefixid+'_list').hide();
				$('#'+this.prefixid+'_nofound').show();
			}
		},
		/* 歌詞開始自動匹配 跟時間軸對應 */
		/**callback時間 jplayer的當前播放時間**/
		start: function(callback) {
			this.callback = callback;
			/* 有歌詞則跳轉到歌詞時間軸 */
			if(this.hasLrc == 1) {
				this.handle = setInterval('$.lrc.jump($.lrc.callback());', this.interval*1000);
			}
		},
		/* 跳到指定時間的歌詞 */
		jump: function(duration) {
			if(typeof(this.handle) != 'number' || typeof(duration) != 'number' || !$.isArray(this.list) || this.list.length < 1) return this.stop();
 
			if(duration < 0) duration = 0;
			if(this.__duration == duration) return;
			duration += 0.2;
			this.__duration = duration;
			duration += this.interval;
 
			var left = 0, right = this.list.length-1, last = right
				pivot = Math.floor(right/2),
				tmpobj = null, tmp = 0, thisobj = this;
 
			/* 二分查詢 */
			while(left <= pivot && pivot <= right) {
				if(this.list[pivot][0] <= duration && (pivot == right || duration < this.list[pivot+1][0])) {
					//if(pivot == right) this.stop();
					break;
				}else if( this.list[pivot][0] > duration ) { /* left */
					right = pivot;
				}else{ /* right */
					left = pivot;
				}
				tmp = left + Math.floor((right - left)/2);
				if(tmp == pivot) break;
				pivot = tmp;
			}
 
			if(pivot == this.pivot) return;
			this.pivot = pivot;
			tmpobj = $('#'+this.prefixid+'_list').children().removeClass(this.hoverClass).eq(pivot).addClass(thisobj.hoverClass);
			tmp = tmpobj.next().offset().top-tmpobj.parent().offset().top - this.hoverTop;
			tmp = tmp > 0 ? tmp * -1 : 0;
			this.animata(tmpobj.parent()[0]).animate({marginTop: tmp + 'px'}, this.interval*1000);
		},
		/* 停止執行歌曲 */
		stop: function() {
			if(typeof(this.handle) == 'number') clearInterval(this.handle);
			this.handle = this.callback = null;
			this.__duration = -1;
			this.regex_time.lastIndex = 0;
			this.list = [];
		},
		animata: function(elem) {
			var f = j = 0, callback, _this={},
				tween = function(t,b,c,d){ return -c*(t/=d)*(t-2) + b; }
			_this.execution = function(key, val, t) {
				var s = (new Date()).getTime(), d = t || 500,
				    b = parseInt(elem.style[key]) || 0,
				    c = val-b;
				(function(){
					var t = (new Date()).getTime() - s;
					if(t>d){
						t=d;
						elem.style[key] = tween(t,b,c,d) + 'px';
						++f == j && callback && callback.apply(elem);
						return true;
					}
					elem.style[key] = tween(t,b,c,d)+'px';
					setTimeout(arguments.callee, 10);
				})();
			}
			_this.animate = function(sty, t, fn){
				callback = fn;
				for(var i in sty){
					j++;
					_this.execution(i,parseInt(sty[i]),t);
				}
			}
			return _this;
		}
	};
})(jQuery);

4、在jplayer初始化中使用如下:
$(document).ready(function(){
	$("#jquery_jplayer_1").jPlayer({
		ready: function () {
			//初始化歌詞資訊(傳入歌詞檔案文字)
			$.lrc.init($('#lrc_content').val());
			$(this).jPlayer("setMedia", {
				title: "Bubble",
				mp3: "mp3/林俊杰 - 曹操.mp3"
			}).jPlayer("play");
		},
		timeupdate: function(event) {
			 if(event.jPlayer.status.currentTime==0){
				time = "";
			 }else {
				time = event.jPlayer.status.currentTime;
			 }
		},
		play: function(event) {
			//點選開始方法呼叫lrc.start歌詞方法 返回時間time
			if($('#lrc_content').val()!==""){
				$.lrc.start(function(){
					return time;
				});
			}else{
			 $(".content").html("沒有字幕");
			}
		},
		swfPath: "js",
		supplied: "mp3",
		wmode: "window",
		smoothPlayBar: true,
		keyEnabled: true,
		remainingDuration: true,
		toggleDuration: true
	});
});

5、這一步不是必要的 只是提供一個我的原始碼給你們參考:
<!DOCTYPE HTML>
<html>
<head>
<title>QQ群:845885222 完整jplayer歌詞同步demo</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link href="skin/pink.flag/jplayer.pink.flag.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="js/jquery-1.8.2.min.js"></script>
<script type="text/javascript" src="js/jquery.jplayer.min.js"></script>
<script type="text/javascript" src="js/jquery.jplayer.lyric.js"></script>
<style type="text/css">
*{ margin:0; padding:0; }
ul, ol, dl { list-style:none; }
.content li.hover{color:red; }
.content{ width:200px;overflow:hidden;padding:10px; text-align: center; font-size:12px;}
</style>
<script type="text/javascript">
//<![CDATA[
$(document).ready(function(){
	$("#jquery_jplayer_1").jPlayer({
		ready: function () {
			//初始化歌詞資訊(傳入歌詞檔案文字)
			$.lrc.init($('#lrc_content').val());
			$(this).jPlayer("setMedia", {
				title: "Bubble",
				mp3: "mp3/林俊杰 - 曹操.mp3"
			}).jPlayer("play");
		},
		timeupdate: function(event) {
			 if(event.jPlayer.status.currentTime==0){
				time = "";
			 }else {
				time = event.jPlayer.status.currentTime;
			 }
		},
		play: function(event) {
			//點選開始方法呼叫lrc.start歌詞方法 返回時間time
			if($('#lrc_content').val()!==""){
				$.lrc.start(function(){
					return time;
				});
			}else{
			 $(".content").html("沒有字幕");
			}
		},
		swfPath: "js",
		supplied: "mp3",
		wmode: "window",
		smoothPlayBar: true,
		keyEnabled: true,
		remainingDuration: true,
		toggleDuration: true
	});
});
//]]>
</script>
</head>
<body>
<!--textarea只是用來儲存歌詞資訊 並不做顯示,如果要修改顯示樣式,修改id="lrc_list"的樣式就行-->
<textarea id="lrc_content" style="display:none;">
[ti:曹操]
[ar:林俊杰]
[al:曹操]
[00:00.03]林俊杰-《曹操》
[00:13.35]作詞:林秋離
[00:20.12]作曲:林俊杰
[00:25.32]
[01:33.46][00:26.82]不是英雄 不讀三國
[01:40.12][00:33.43]若是英雄 怎麼能不懂寂寞
[02:39.68][01:46.34][00:39.63]獨自走下長阪坡 月光太溫柔
[02:43.20][01:49.82][00:43.15]曹操不囉嗦 一心要那荊州
[02:46.75][01:53.48][00:46.83]用陰謀 陽謀 明說 暗奪的摸
[02:53.44][02:00.10][00:53.50]東漢末年分三國
[02:56.37][02:03.15][00:56.52]烽火連天不休
[03:00.12][02:06.75][01:00.17]兒女情長 被亂世左右
[03:05.04][02:11.71][01:05.12]誰來煮酒
[03:06.78][02:13.45][01:06.84]爾虞我詐是三國
[03:09.85][02:16.43][01:09.73]說不清對與錯
[03:13.38][02:20.11][01:13.48]紛紛擾擾 千百年以後
[03:18.44][02:25.06][01:18.45]一切又從頭
[03:25.99][02:30.17][01:26.81]喔……
[88:88:88]
</textarea>
<div id="jquery_jplayer_1" class="jp-jplayer"></div>
<div id="jp_container_1" class="jp-audio">
	<div class="jp-type-single">
		<div class="jp-gui jp-interface">
			<ul class="jp-controls">
				<li><a href="javascript:;" class="jp-play" tabindex="1">play</a></li>
				<li><a href="javascript:;" class="jp-pause" tabindex="1">pause</a></li>
				<li><a href="javascript:;" class="jp-stop" tabindex="1">stop</a></li>
				<li><a href="javascript:;" class="jp-mute" tabindex="1" title="mute">mute</a></li>
				<li><a href="javascript:;" class="jp-unmute" tabindex="1" title="unmute">unmute</a></li>
				<li><a href="javascript:;" class="jp-volume-max" tabindex="1" title="max volume">max volume</a></li>
			</ul>
			<div class="jp-progress">
				<div class="jp-seek-bar">
					<div class="jp-play-bar"></div>

				</div>
			</div>
			<div class="jp-volume-bar">
				<div class="jp-volume-bar-value"></div>
			</div>
			<div class="jp-current-time"></div>
			<div class="jp-duration"></div>
			<ul class="jp-toggles">
				<li><a href="javascript:;" class="jp-repeat" tabindex="1" title="repeat">repeat</a></li>
				<li><a href="javascript:;" class="jp-repeat-off" tabindex="1" title="repeat off">repeat off</a></li>
			</ul>
		</div>
		<div class="jp-details">
			<ul>
				<li><span class="jp-title"></span></li>
			</ul>
		</div>
		<div class="jp-no-solution">
			<span>Update Required</span>
			To play the media you will need to either update your browser to a recent version or update your <a href="http://get.adobe.com/flashplayer/" target="_blank">Flash plugin</a>.
		</div>
	</div>
</div>

<div class="content">
	<ul id="lrc_list">
		載入歌詞……
	</ul>
</div>
</body>
</html>