用HTML5的Audio標籤作一個歌詞同步的效果

HTML5出來這麼久了,可是關於它裏面的audio標籤也就用過那麼一次,固然還僅僅只是把這個標籤插入到了頁面中。此次呢就恰好趁着幫朋友作幾個頁面,拿這個audio標籤來練練手。css

首先你須要向頁面中插入一個audio標籤,注意這裏最好不要設置loop='loop',這個屬性使用來設置循環播放的,由於到後面須要使用ended屬性的時候,若是loop被設置爲loop的話,ended屬性將一直是false。html

autoplay='autoplay'設置頁面加載後自動播放音樂,preload和autoplay屬性的做用是同樣的,若是標籤中出現了autoplay屬性,那麼preload屬性將被忽略。html5

controls='controls'設置顯示音樂的控制條。node

<audio src="music/Yesterday Once More.mp3" id="aud" autoplay="autoplay" controls="controls" preload="auto">
    您的瀏覽器不支持audio屬性,請更換瀏覽器在進行瀏覽。
</audio>

有了這個標籤以後,那麼恭喜你,你的頁面已經能夠播放音樂了。可是這樣會不會顯得頁面太過於單調了,因而我又給頁面添加了一些東西,讓歌詞可以同步的顯示在頁面上,還可以選擇要播放的音樂。那麼先要作成這樣的效果,咱們就得要去下載一些lrc格式的歌詞文件,而後你須要把這些音樂格式化一番。由於剛開始的音樂文件是這樣的web

咱們須要把每一句歌詞插入到一個二位數組裏面,通過格式化以後歌詞就變成這樣的格式了正則表達式

這裏附上格式化歌詞的代碼(固然這裏的代碼是從別的地方拿來用的,原版在這裏http://www.cnblogs.com/Wayou/p/sync_lyric_with_html5_audio.html數組

//歌詞同步部分
    function parseLyric(text) {
        //將文本分隔成一行一行,存入數組
        var lines = text.split('\n'),
        //用於匹配時間的正則表達式,匹配的結果相似[xx:xx.xx]
                pattern = /\[\d{2}:\d{2}.\d{2}\]/g,
        //保存最終結果的數組
                result = [];
        //去掉不含時間的行
        while (!pattern.test(lines[0])) {
            lines = lines.slice(1);
        };
        //上面用'\n'生成生成數組時,結果中最後一個爲空元素,這裏將去掉
        lines[lines.length - 1].length === 0 && lines.pop();
        lines.forEach(function(v /*數組元素值*/ , i /*元素索引*/ , a /*數組自己*/ ) {
            //提取出時間[xx:xx.xx]
            var time = v.match(pattern),
            //提取歌詞
                    value = v.replace(pattern, '');
            //由於一行裏面可能有多個時間,因此time有多是[xx:xx.xx][xx:xx.xx][xx:xx.xx]的形式,須要進一步分隔
            time.forEach(function(v1, i1, a1) {
                //去掉時間裏的中括號獲得xx:xx.xx
                var t = v1.slice(1, -1).split(':');
                //將結果壓入最終數組
                result.push([parseInt(t[0], 10) * 60 + parseFloat(t[1]), value]);
            });
        });
        //最後將結果數組中的元素按時間大小排序,以便保存以後正常顯示歌詞
        result.sort(function(a, b) {
            return a[0] - b[0];
        });
        return result;
    }

到了這裏咱們就可以很容易的使用每首音樂的歌詞了,咱們須要有一個function來得到歌詞,而且讓他同步的顯示在頁面上,可以正常的切換音樂。下面附上代碼。瀏覽器

function fn(sgname){
        $.get('music/'+sgname+'.lrc',function(data){
            var str=parseLyric(data);
            for(var i=0,li;i<str.length;i++){
                li=$('<li>'+str[i][1]+'</li>');
                $('#gc ul').append(li);
            }
            $('#aud')[0].ontimeupdate=function(){//視屏 音頻當前的播放位置發生改變時觸發
                for (var i = 0, l = str.length; i < l; i++) {
                    if (this.currentTime /*當前播放的時間*/ > str[i][0]) {
                        //顯示到頁面
                        $('#gc ul').css('top',-i*40+200+'px'); //讓歌詞向上移動
                        $('#gc ul li').css('color','#fff');
                        $('#gc ul li:nth-child('+(i+1)+')').css('color','red'); //高亮顯示當前播放的哪一句歌詞
                    }
                }
                if(this.ended){ //判斷當前播放的音樂是否播放完畢
                    var songslen=$('.songs_list li').length;
                    for(var i= 0,val;i<songslen;i++){
                        val=$('.songs_list li:nth-child('+(i+1)+')').text();
                        if(val==sgname){
                            i=(i==(songslen-1))?1:i+2;
                            sgname=$('.songs_list li:nth-child('+i+')').text(); //音樂播放完畢以後切換下一首音樂
                            $('#gc ul').empty(); //清空歌詞
                            $('#aud').attr('src','music/'+sgname+'.mp3');
                            fn(sgname);
                            return;
                        }
                    }
                }
            };
        });
    }
fn($('.songs_list li:nth-child(1)').text());

那麼到了這裏你的音樂歌詞已經可以正常的同步顯示在頁面上了。不過還缺乏一個東西,就是一個音樂的列表,我但願可以點擊這個列表裏的音樂,從而播放該音樂,下面附上代碼。app

HTML代碼oop

<div class="songs_cnt">
    <ul class="songs_list">
        <li>Yesterday Once More</li>
        <li>You Are Beautiful</li>
    </ul>
    <button class="sel_song"><br/><br/></button>
</div>
<div id="gc">
    <ul></ul>
</div>

css代碼

#gc{
            width: 400px;
            height: 400px;
            background: transparent;
            margin: 100px auto;
            color: #fff;
            font-size: 18px;
            overflow: hidden;
            position: relative;
        }
        #gc ul{
            position: absolute;
            top: 200px;
        }
        #gc ul li{
            text-align: center;
            height: 40px;
            line-height: 40px;
        }
        .songs_cnt{
            float: left;
            margin-top: 200px;
            position: relative;
        }
        .songs_list{
            background-color: rgba(0,0,0,.2);
            border-radius: 5px;
            float: left;
            width: 250px;
            padding: 15px;
            margin-left: -280px;
        }
        .songs_list li{
            height: 40px;
            line-height: 40px;
            font-size: 16px;
            color: rgba(255,255,255,.8);
            cursor: pointer;
        }
        .songs_list li:hover{
            font-size: 20px;
            color: rgba(255,23,140,.6);
        }
        .sel_song{
            position: absolute;
            top: 50%;
            width: 40px;
            height: 80px;
            margin-top: -40px;
            font-size: 16px;
            text-align: center;
            background-color: transparent;
            border: 1px solid #2DCB70;
            font-weight: bold;
            cursor: pointer;
            border-radius: 3px;
            font-family: sans-serif;
            transition:all 2s;
            -moz-transition:all 2s;
            -webkit-transition:all 2s;
            -o-transition:all 2s;
        }
        .sel_song:hover{
            color: #fff;
            background-color: #2DCB70;
        }
        .songs_list li.active{
            color: #f00;
        }

js代碼

$('.songs_list li:nth-child(1)').addClass('active');

    $('.songs_cnt').mouseenter(function () {
        var e=event||window.event;
        var tag= e.target||e.srcElement;
        if(tag.nodeName=='BUTTON'){
            $('.songs_list').animate({'marginLeft':'0px'},'slow');
        }
    });
    $('.songs_cnt').mouseleave(function () {
        $('.songs_list').animate({'marginLeft':'-280px'},'slow');
    });

    $('.songs_list li').each(function () {
        $(this).click(function () {
            $('#aud').attr('src','music/'+$(this).text()+'.mp3');
            $('#gc ul').empty();
            fn($(this).text());
            $('.songs_list li').removeClass('active');
            $(this).addClass('active');
        });
    })

好了,到了這裏,那麼你的這個歌詞同步的效果的一些功能差很少都有了,今天也就到這裏了。

相關文章
相關標籤/搜索