简易播放器

245 阅读1分钟
<!DOCTYPE >
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>简易的音乐播放器</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        ul {
            list-style: none;
        }

        ul li {
            margin: 20px 20px;
            padding: 10px 5px;
            border-radius: 3px;
        }

        ul li.active {
            background-color: #D2E2F3;
        }
    </style>
</head>

<body>
    <div id="app">
        <audio :src="currentSrc" controls autoplay @ended='handleEnded'></audio>
        <ul>
            <li :class='{active:index===currentIndex}' v-for='(item,index) in musicData' :key='item.id'
                @click='handleClick(item.songSrc,index)'>
                <h2>{{item.id}}-歌名:{{item.name}}</h2>
                <p>{{item.autor}}</p>
            </li>
        </ul>
        <button @click = 'handleNext'>下一首</button>
        <button @click ='handlePrve'>上一首</button>
    </div>
    <script src="./vue.js"></script>
    <script>
        const musicData = [{
            id: 1,
            name: '离骚',
            autor: '艾辰',
            songSrc: './music/艾辰 - 离骚.mp3'
        },
        {
            id: 2,
            name: '永不失联的爱 (2020中国好声音第3期现场)',
            autor: '单依纯',
            songSrc: './music/单依纯 - 永不失联的爱 (2020中国好声音第3期现场).mp3'
        },
        {
            id: 3,
            name: '漂洋过海来看你',
            autor: '刘明湘',
            songSrc: './music/刘明湘 - 漂洋过海来看你.mp3'
        },
        {
            id: 4,
            name: '一定要爱你 (网络版)',
            autor: '田一龙',
            songSrc: './music/田一龙 - 一定要爱你 (网络版).mp3'
        }]
        new Vue({
            el: '#app',
            data: {
                musicData,
                currentSrc: './music/艾辰 - 离骚.mp3',
                currentIndex: 0
            },
            methods: {
                handleClick(src, index) {
                    this.currentSrc = src;
                    this.currentIndex = index;
                },
                handleEnded() {
                    this.handleNext();
                },
                handleNext() {
                    this.currentIndex++;
                    if (this.currentIndex === this.musicData.length) {
                        this.currentIndex = 0;
                    }
                    this.currentSrc = this.musicData[this.currentIndex].songSrc
                },

                 handlePrve(){
                    this.currentIndex--;
                    if (this.currentIndex < 0) {
                        this.currentIndex = this.musicData.length - 1;
                    }
                 }
            }
        })
    </script>
</body>

</html>