react 多音频续播的实现【一定收藏,江湖秘籍】

330 阅读1分钟

话不多少直接上代码

import React from 'react';
import './style.scss';

export default class Home extends React.Component {
   // 音频数组 可自行添加
    musicArray = [
       'http://ws.stream.qqmusic.qq.com/C400002c5b4919Au5Z.m4a?guid=213254905&vkey=0C53A42E1DF0A4BD62DC1FFD8945D846B7825D1795B5ABF5521BA27F6B77624134D69A7381114B2BD87E2868D74E46E603B6FFCDB72137EE&uin=0&fromtag=66',
       'http://ws.stream.qqmusic.qq.com/C400002c5b4919Au5Z.m4a?guid=213254905&vkey=0C53A42E1DF0A4BD62DC1FFD8945D846B7825D1795B5ABF5521BA27F6B77624134D69A7381114B2BD87E2868D74E46E603B6FFCDB72137EE&uin=0&fromtag=66'
    ]
    index = 0; // 音频数组索引
    audioValue =null // audio对象

    state = {
        playText: '点击播放', // 播放按钮文字
        isPlay: false, // 是否是播放
        currentUrl: '' // 当前音频地址 
    }

    /**
     * 音频播放事件
     **/
    playAudio = () => {
        const {currentUrl} = this.state;
        this.setState({
            isPlay: true,
            currentUrl: this.index === this.musicArray.length - 1 ? this.musicArray[this.musicArray.length - 1] : this.index === 0 ? this.musicArray[0] : currentUrl
        }, () => {
            this.audioValue.play();
        });
    }

    /**
     * 音频播放结束后更新音频地址
     **/
    switchSrc = () => {
        this.index++;
        this.audioValue.src = this.musicArray[this.index];
        this.setState({
            currentUrl: this.index <= this.musicArray.length ? this.musicArray[this.index] : '',
            isPlay: this.index !== this.musicArray.length - 1
        }, () => {
            this.audioValue.play();
            if (this.index === this.musicArray.length) {
                this.index = 0;
                this.audioValue.pause();
            }
        });
    }

    render() {
        const {playText, currentUrl} = this.state;
        return (
            <div className="home">
                <div className="play-button" onClick={this.playAudio}>{playText}</div>
                <audio ref={(audio) => { this.audioValue = audio; }} src={currentUrl} onEnded={this.switchSrc}></audio>
            </div>
        );
    }
};