import { ComponentClass } from 'react' import Taro, { Component } from '@tarojs/taro' import { View, Image } from '@tarojs/components' import './index.scss' type PageOwnProps = { className?: string voiceUrl: any voiceName: any } type IProps = PageOwnProps interface Index { props: IProps; } class Index extends Component { static options = { addGlobalClass: true } state = { playing: false, audioTime: null, playTime: '00:00' } innerAudioContext formatTime(second) { const seconds = (Math.floor(second % 60) + '').padStart(2, '0'); const mins = (Math.floor(second % 3600 / 60) + '').padStart(2, '0') return `${mins}:${seconds}` } componentWillMount() { if (process.env.TARO_ENV === 'weapp' && this.props.voiceUrl) { this.innerAudioContext = Taro.createInnerAudioContext() this.innerAudioContext.autoplay = false this.innerAudioContext.src = this.props.voiceUrl this.innerAudioContext.onPlay(e => { this.setState({ audioTime: this.formatTime(this.innerAudioContext.duration) }) }) this.innerAudioContext.onTimeUpdate(e => { this.setState({ playTime: this.formatTime(this.innerAudioContext.currentTime) }) this.setState({ audioTime: this.formatTime(this.innerAudioContext.duration) }) }) this.innerAudioContext.onStop(e => { this.setState({ playTime: '00:00' }) }) this.innerAudioContext.onError((res) => { Taro.showToast({ title: res.errMsg, icon: 'none' }) }) } } play = () => { if (this.state.playing) { // 暂停 this.innerAudioContext.stop() this.setState({ playing: false }) } else { // 播放 this.innerAudioContext.play() this.setState({ playing: true }) } } render() { return ( {this.props.voiceName} {this.state.playTime} {this.state.audioTime || ''} ) } } export default Index as ComponentClass