如何使用 React 在音频元素上设置 srcObject [英] How to set srcObject on audio element with React
问题描述
我一直在尝试在 React 中设置音频标签的 src
属性,但曲目从未播放.
I've been trying to set the src
attribute of an audio tag in React, but the track never plays.
playTrack(track) {
const stream = new MediaStream()
stream.addTrack(track)
this.setState(() => ({ stream }))
}
render() {
return (
<audio src={this.state.stream || null} controls volume="true" autoPlay />
)
}
当我检查 chrome 调试器时,它显示音频标签已将 [MediaStream]
设置为其源,但没有播放任何内容,所有控件都保持灰色.
When I check in the chrome debugger it shows that the audio tag has [MediaStream]
set as its source, but nothing plays and all the controls remained grayed out.
这样做而不是设置状态有效,但我认为这在 React 中很不受欢迎.
Doing this instead of setting the state works, but I presume this is highly frowned upon in React.
const audio = document.querySelector('audio')
audio.srcObject = stream
推荐答案
如果在状态中存储流不是必需的,那么您可以使用 ref<更新
srcObject
属性/代码>:
If storing the stream in the state is not a requirement, then you can update the srcObject
property using a ref
:
playTrack(track) {
const stream = new MediaStream()
stream.addTrack(track)
this.audio.srcObject = stream;
}
render() {
return (
<audio ref={audio => {this.audio = audio}} controls volume="true" autoPlay />
)
}
如果你确实需要从状态访问流,你可以试试这个
If you do need to access the stream from the state you can try this
<audio ref={audio => { audio.srcObject = this.state.stream }} />
src={this.state.stream}
不起作用的原因是因为 src
需要一个表示音频资源 url 的字符串,而 this.state.stream
是一个 MediaStream
对象.
The reason src={this.state.stream}
doesn't work is because src
expects a string that represents the url of the audio resource while this.state.stream
is a MediaStream
object.
audio.src
和 audio.srcObject
是不同的属性,需要不同的值类型.
audio.src
and audio.srcObject
are different properties that expect different value types.
这篇关于如何使用 React 在音频元素上设置 srcObject的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!