Hi all! I am trying to play some audio. If I have ...
# react
j
Hi all! I am trying to play some audio. If I have this audio react element:
Copy code
audio {
    attrs {
        src="sounds/time.mp3"
    }
}
How can I run play() on it? 🙂
I can conditionally add/remove the element in conjunction with autoPlay to make it play/stop but it feels very dirty
Copy code
if (viewState.playAudio) {
            audio {
                attrs {
                    src = "sounds/time.mp3"
                    autoPlay = true
                }

            }
        }
btw I want to have my own controls
Okay figured it out
Copy code
ref {
                findDOMNode(it).asDynamic().play()
            }
👍 1
t
Looks like you need create ref before
👍 1
j
Copy code
audio {
    attrs {
        src = "sounds/time.mp3"
    }

    ref = createRef<Audio>().apply {
        useEffect(listOf(viewState.playAudio)) {
            if (viewState.playAudio) {
                current?.play()
            } else {
                current?.pause()
            }
        }
    }
}
@turansky something like this? 🙂
🚫 1
😢 1
t
Copy code
val audioRef = createRef<Audio>()
        useEffect(listOf(viewState.playAudio)) {
  val audio = audioRef.current!!
  if (viewState.playAudio) {
    audio.play()
  } else {
    audio.pause()
  }
}

// render
audio {
    ref = audioRef
    attrs {
        src = "sounds/time.mp3"
    }
}
👍 1
j
Ah because it would recreate the ref otherwise. I will then use a state or something (I have a functional component)
Copy code
val audioRef = useState {
                createRef<Audio>()
            }.first.apply {
                useEffect(listOf(viewState.playAudio)) {
                    if (viewState.playAudio) {
                        current?.play()
                    } else {
                        current?.pause()
                    }
                }
            }
            ref = audioRef