注: react 环境 ,图片自行替换, 支持多音频切换播放,没有暂停续播功能
    需要自行在外部父组件加入

    1. import React, { Component } from 'react'
    2. import audio_play_1 from 'Images/audio_play_1.svg'
    3. import audio_play_2 from 'Images/audio_play_2.svg'
    4. import audio_play_3 from 'Images/audio_play_3.svg'
    5. import audio_play_0 from 'Images/audio_icon.svg'
    6. export default class AudioPlayBtn extends Component {
    7. constructor(props) {
    8. super(props)
    9. this.state = {
    10. audioBtnImg: audio_play_0,
    11. animationFlag: false
    12. }
    13. this.timer = null
    14. this.imgCount = 0
    15. this.imgs = {
    16. audio_play_0: audio_play_0,
    17. audio_play_1: audio_play_1,
    18. audio_play_2: audio_play_2,
    19. audio_play_3: audio_play_3
    20. }
    21. }
    22. componentDidMount() {
    23. this.addEventListenerFn()
    24. }
    25. closeAudioPlay() {
    26. const audio = document.getElementById('chatAudio')
    27. audio.url = ''
    28. window.clearInterval(this.timer)
    29. this.timer = null
    30. this.imgCount = 0
    31. this.setState({
    32. audioBtnImg: audio_play_0
    33. })
    34. }
    35. /** 播放音频 */
    36. startAudio() {
    37. const audio = document.getElementById('chatAudio')
    38. if (this.timer) return false
    39. audio.src = this.props.url
    40. audio.play()
    41. }
    42. changeFlag(flag) {
    43. if (flag) {
    44. this.timer = window.setInterval(() => {
    45. if (this.imgCount >= 3) {
    46. this.imgCount = 0
    47. }
    48. this.setState({
    49. audioBtnImg: this.imgs[`audio_play_${ this.imgCount }`]
    50. })
    51. this.imgCount++
    52. }, 400)
    53. } else {
    54. this.closeAudioPlay()
    55. }
    56. }
    57. addEventListenerFn() {
    58. const that = this
    59. const audio = document.getElementById('chatAudio')
    60. if (audio) {
    61. audio.loop = false
    62. audio.addEventListener('ended', function() {
    63. that.closeAudioPlay()
    64. }, false)
    65. audio.addEventListener('timeupdate', function() {
    66. if (audio.currentSrc !== '' && audio.currentSrc !== that.props.url) {
    67. that.closeAudioPlay()
    68. } else {
    69. if (!that.timer) that.changeFlag(true)
    70. }
    71. })
    72. }
    73. }
    74. render() {
    75. return (
    76. <div onClick={ this.startAudio.bind(this) }>
    77. <img src={ this.state.audioBtnImg } alt='' />
    78. </div>
    79. )
    80. }
    81. }