Sam Mason
Sam Mason

Reputation: 1037

Audio object not restarting stream when being remounted with React

I have a react component that contains an Audio object that is a playing a livestream. When the component initially loads it starts playing, however if I unmount the component and then remount it the play button does not work and the stream doesn't restart.

Here is the code for the component and lifecycle methods:

import React from 'react'
import compose from 'recompose/compose'
import lifecycle from 'recompose/lifecycle'

const enhance = compose(
  lifecycle({
    componentDidMount() {
     this.audio = new Audio()
     this.audio.src = 'http://some-stream-url.com'
     this.audio.play()
     this.audio.muted = true
    },
    componentDidUpdate() {
     this.audio.muted = !this.props.playing
    },
    componentWillUnmount() {
     this.audio = ''
     this.audio = null
    }
 })
)

const Player = (props) => null

export default enhance(Player)

Upvotes: 1

Views: 473

Answers (1)

user1399844
user1399844

Reputation:

Stop audio and restart current time.

componentWillUnmount() {
   this.audio.pause()
   this.audio.currentTime = 0
}

Upvotes: 1

Related Questions