我在我的项目中使用 Twillio JS API 来显示来自多个来源的视频输出。此 API 生成可附加到页面的 DOM 视频/音频元素的枚举,如下所示:
let tracks = TwillioVideo.createLocalTracks({
video: { deviceId: this.state.selectedVideoInput.deviceId },
audio: { deviceId: this.state.selectedAudioInput.deviceId }
}
//Find dom element to attach tracks to
let previewContainer = document.getElementById('local-media')
//Attach all tracks
this.setState({localTracks: tracks})
tracks.forEach(track => previewContainer.appendChild(track.attach()))
track.attach()
生成一个可以附加的 dom 元素,但它不是我可以放入 React 状态的东西,所以它可以像这样呈现:
<div id="local-media">{this.state.localTracks.map(track => track.attach()}</div>
如果我真的尝试这样做,我会得到:
Unhandled Rejection (Invariant Violation): Objects are not valid as a React child (found: [object HTMLAudioElement]). If you meant to render a collection of children, use an array instead.
编辑 1: 通过这样做,我能够摆脱错误:
{this.state.localTracks.map(track => track.attach().Element)}
但它不返回可呈现的 html,而是返回 undefined
最佳答案
此处为 Twilio 开发人员布道师。
attach
method in Twilio Video可以接受一个参数,它是一个 HTMLMediaElement
,并将媒体附加到该元素。
我建议您创建一个可用于为每个媒体轨道呈现媒体的组件,然后使用 React refs获取指向 DOM 元素的指针。
像这样:
import React, { Component, createRef } from 'react';
class Participant extends Component {
constructor(props) {
super(props);
this.video = createRef();
this.audio = createRef();
this.trackAdded = this.trackAdded.bind(this);
}
trackAdded(track) {
if (track.kind === 'video') {
track.attach(this.video.current);
} else if (track.kind === 'audio') {
track.attach(this.audio.current);
}
}
componentDidMount() {
const videoTrack = Array.from(
this.props.participant.videoTracks.values()
)[0];
if (videoTrack) {
videoTrack.attach(this.video.current);
}
const audioTrack = Array.from(
this.props.participant.audioTracks.values()
)[0];
if (audioTrack) {
audioTrack.attach(this.audio.current);
}
this.props.participant.on('trackAdded', this.trackAdded);
}
render() {
return (
<div className="participant">
<h3>{this.props.participant.identity}</h3>
<video ref={this.video} autoPlay={true} muted={true} />
<audio ref={this.audio} autoPlay={true} muted={true} />
</div>
);
}
}
export default Participant;
然后,对于聊天中的每个参与者,您可以呈现这些组件之一。
如果这有帮助,请告诉我。
关于javascript - 使用 React 渲染 HTMLAudioElement DOM 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57994095/