注: react 环境 ,图片自行替换, 支持多音频切换播放,没有暂停续播功能
需要自行在外部父组件加入
import React, { Component } from 'react'import audio_play_1 from 'Images/audio_play_1.svg'import audio_play_2 from 'Images/audio_play_2.svg'import audio_play_3 from 'Images/audio_play_3.svg'import audio_play_0 from 'Images/audio_icon.svg'export default class AudioPlayBtn extends Component {constructor(props) {super(props)this.state = {audioBtnImg: audio_play_0,animationFlag: false}this.timer = nullthis.imgCount = 0this.imgs = {audio_play_0: audio_play_0,audio_play_1: audio_play_1,audio_play_2: audio_play_2,audio_play_3: audio_play_3}}componentDidMount() {this.addEventListenerFn()}closeAudioPlay() {const audio = document.getElementById('chatAudio')audio.url = ''window.clearInterval(this.timer)this.timer = nullthis.imgCount = 0this.setState({audioBtnImg: audio_play_0})}/** 播放音频 */startAudio() {const audio = document.getElementById('chatAudio')if (this.timer) return falseaudio.src = this.props.urlaudio.play()}changeFlag(flag) {if (flag) {this.timer = window.setInterval(() => {if (this.imgCount >= 3) {this.imgCount = 0}this.setState({audioBtnImg: this.imgs[`audio_play_${ this.imgCount }`]})this.imgCount++}, 400)} else {this.closeAudioPlay()}}addEventListenerFn() {const that = thisconst audio = document.getElementById('chatAudio')if (audio) {audio.loop = falseaudio.addEventListener('ended', function() {that.closeAudioPlay()}, false)audio.addEventListener('timeupdate', function() {if (audio.currentSrc !== '' && audio.currentSrc !== that.props.url) {that.closeAudioPlay()} else {if (!that.timer) that.changeFlag(true)}})}}render() {return (<div onClick={ this.startAudio.bind(this) }><img src={ this.state.audioBtnImg } alt='' /></div>)}}
