preface

The company has a unit project, which needs to read voice files and play them. In fact, audio can be used to introduce a play link, which does not need too many functions. Later, I thought that the website can also put a small player plug-in, so I simply checked the API related to audio, learned related skills and shared them with everyone

The complete code

The entire code is very simple, with some audio-API comments written in the HTML behind

<template>
    <div class="music">
        <div class="music__main">
            <div :class="['music__main__cover',isPlay ? 'active' : '']" @click="play">
                <img src="@/assets/meet.jpg" />
            </div>
            <div class="music__main__timeBar">
                <div class="time">
                    <span>{{ realMusicTime }}</span>
                    <span>{{ totalMusicTime }}</span>
                </div>
                <div class="bar" ref="bar" @click="handClickBar">
                    <div class="bar__slid" ref="slid" @click="handClickBar"></div>
                </div>
            </div>
        </div>
        <div class="music__btn">
            <i class="el-icon-refresh" @click="switchMusic"></i>
        </div>
        <div class="music__mask"></div>
        <audio ref="music" :src="audioSrc"></audio>
    </div>
</template>
Copy the code

js

<script>
export default {
    data() {
        this.audioSrcs = [
            'https://music.163.com/song/media/outer/url?id=1369798757.mp3'./ / grain in ear
            'http://m7.music.126.net/20200620010555/e89a481dbb579809feccc4c7e1eaf50b/ymusic/a9c1/47f7/e72a/eeca0e403e1aa21dc60ca590b e3db3f0.mp3'./ / later
            'http://m7.music.126.net/20200620101114/4b5eaebd7e28eda2a6cda8e1e8e1972e/ymusic/545e/065a/530b/c413a59407100320b8f9da233 b35f938.mp3'.// Your answer
            'http://m7.music.126.net/20200620101206/6d89785d9f392dc06889d6142c1c4a3a/ymusic/060f/0e0e/510f/1edeffdfca9d5fb74fd0fe02e dd9bbba.mp3'.// The girl said to me
            'http://m7.music.126.net/20200620101232/b8fb9367db300c11fee6d134a6721471/ymusic/40f6/674f/125c/83af64a31bd4b1d82a500771b 87ddf3f.mp3'./ / side face
            'http://m7.music.126.net/20200620101440/62d4f101f0844469e8706d73175d98d4/ymusic/5309/065c/070b/dc1aee8fb016a88606530ad5a 10ba676.mp3'.// You in the distance
        ];
        return {
            isPlay: false.realMusicTime: "Prefer".totalMusicTime: "Prefer".audioSrc: this.audioSrcs[0]}; }, created() { }, mounted() {this.watchMusicTime();
    },
    methods: {
        play() {
            if (this.music.paused) {
                this.music.play();
                this.isPlay = true;
            } else {
                this.music.pause();
                this.isPlay = false; }},// Processing time
        handlMusicTime() {
            // Displays the current playback progress in seconds
            let timeDisplay = Math.floor(this.music.currentTime); // Get the real-time time
            / / minute
            let minute = parseInt(timeDisplay / 60);
            if (minute < 10) {
                minute = "0" + minute;
            }
            / / SEC.
            let second = Math.round(timeDisplay % 60);
            if (second < 10) {
                second = "0" + second;
            }
            this.realMusicTime = minute + ":" + second;
        },
        // Process the progress bar
        handMusicBar() {
            let slid = this.$refs.slid;
            let duration = this.music.duration;
            let x = ((this.music.currentTime / duration) * 100).toFixed(2) + "%";
            slid.style.width = x;
        },
        // Handle the click progress bar event
        handClickBar(e) {
            const barTotalWidth = this.bar.offsetWidth; // Bar total width
            const rect = e.target.getBoundingClientRect(); // The distance to the right of the element from the page margin returns up, down, left, and right
            let length = e.pageX - rect.left;
            this.music.currentTime = length / barTotalWidth * this.music.duration; // Calculate the playing time position percentage * total time
            this.$nextTick((a)= > {
                this.music.play();
                this.isPlay = true; })},// Switch songs
        switchMusic() {
            this.isPlay = false;
            this.audioSrc = this.audioSrcs[Math.floor(Math.random() * 5)];
            this.music.load()
            // When the file is downloaded, you can use the canplay event instead of waiting until the file is downloaded
            this.music.addEventListener("canplaythrough", () = > {this.music.play();
                this.isPlay = true;
            });
        },
        // Use event listening to catch events
        watchMusicTime() {
            this.music = this.$refs.music;
            this.bar = this.$refs.bar;
            this.music.addEventListener(
                "timeupdate", () = > {this.handlMusicTime();
                    this.$nextTick((a)= > {
                        this.handMusicBar(); })},false
            );
            // End of playback
            this.music.addEventListener("ended", () = > {this.switchMusic(); // Auto play
            });
            // The captured audio file is ready
            // The oncanPlay event is triggered when the media file is ready to play
            this.music.oncanplaythrough = (a)= > {
                let time = this.music.duration;
                / / minute
                let minutes = parseInt(time / 60);
                if (minutes < 10) {
                    minutes = "0" + minutes;
                }
                / / SEC.
                let seconds = Math.round(time % 60);
                if (seconds < 10) {
                    seconds = "0" + seconds;
                }
                this.totalMusicTime = minutes + ":"+ seconds; }; }}};</script>
Copy the code

less

<style lang="less"> @keyframes musicRotate { from { transform: rotate(0); } to { transform: rotate(360deg); } } .music { width: 500px; margin: 0 auto; border-radius: 15px; position: relative; padding: 30px; box-sizing: border-box; overflow: hidden; &__main { display: flex; &__cover { width: 80px; height: 80px; overflow: hidden; border-radius: 50%; background-color: #dddddd; cursor: pointer; animation: musicRotate 10s linear infinite; animation-play-state: paused; Img {width: 100%; height: 100%; } &.active { animation-play-state: running; }} &__timebar {flex: 1; display: flex; flex-direction: column; justify-content: space-evenly; padding-left: 20px; box-sizing: border-box; .time { display: flex; justify-content: space-between; color: #fff; span { font-size: 19px; line-height: 1; } } .bar { height: 8px; background-color: #fbfbfb; border-radius: 8px; position: relative; border-radius: 8px; overflow: hidden; cursor: pointer; &__slid { position: absolute; left: 0; top: 0; background-color: #e24d80; height: 100%; width: 0; The transition: width 0.3 s; } } } } &__btn { position: absolute; right: 30px; top: 10px; i { font-size: 18px; color: #fff; cursor: pointer; } } &__mask { background-image: url('.. /.. /assets/meet.jpg'); z-index: -2; background-repeat: no-repeat; background-size: cover; background-position: 50%; filter: blur(15px); Opacity: 0.5; The transition: all 0.8 s; position: absolute; top: 0; right: 0; left: 0; bottom: 0; &::before { position: absolute; top: 0; right: 0; left: 0; bottom: 0; z-index: -1; content: ''; Background: rgba(0, 0, 0, 0.08); } } } </style>Copy the code

Github complete code with vue simple to write a music player component

Audio related

HTML Audio Basic API complete guide to use