第零步媒体流展示容器
远端流媒体服务器用的是kurento,怎么使用可以到kurento的官网学习
一个是本地数据展示,另一个是远程数据展示
<View style={styles.video_container}>
{this.state.stream && <RTCView streamURL={this.state.stream.toURL()} style={styles.remote_video_style} />}
{this.state.remoteStream && <RTCView streamURL={this.state.remoteStream.toURL()} style={styles.local_video_style} />}
</View>
第一步获取本地媒体流
async start() {
if (!this.state.stream) {
let s;
try {
var constraints = {
video: true,
audio: true
}
s = await mediaDevices.getUserMedia(constraints);
this.setState({ stream: s })
this.call(s)
} catch (e) {
console.error(e);
}
}
}
第二步创建peerConnection
1、创建(这里不加stun/turn配置,貌似会连接不成功)
stun/turn服务器需要自己配置
var configuration = {
iceServers: [{
urls: "stun:stun.services.mozilla.com",
username: "louis@mozilla.com",
credential: "webrtcdemo"
}]
};
this.#peerConnection = new RTCPeerConnection(configuration);
2、 监听事件
this.#peerConnection.onicecandidate = (e) => {
if (e.candidate != null) {
this.sendMessage({
id: 'ADD_ICE_CANDIDATE',
candidate: e.candidate
});
}
}
this.#peerConnection.onconnectionstatechange = (e) => {
switch (this.#peerConnection.connectionState) {
case "new":
console.log("建立连接")
break;
case "connecting":
console.log("正在连接")
break;
case "connected":
console.log("完全连接")
const streams = this.#peerConnection.getRemoteStreams();
this.setState({remoteStream: streams[0]})
console.log("流的数量:" + streams.length)
break;
case "disconnected":
console.log("断开连接")
break;
case "failed":
console.log("连接失败")
break;
case "closed":
console.log("连接已经被关闭")
break;
}
}
3、添加传输媒体流,并创建offer
this.#peerConnection.addStream(stream)
const offerOptions = {
offerToRecieveAudio: 1,
offerToRecieveVideo: 1
}
const offer = await this.#peerConnection.createOffer(offerOptions);
this.#peerConnection.setLocalDescription(offer);
this.sendMessage({
id: 'PROCESS_SDP_OFFER',
sdpOffer: offer.sdp,
});
4、设置远端setRemoteDescription
handleProcessSdpAnswer(jsonMessage) {
if (this.#peerConnection == null) {
return;
}
const answer = new RTCSessionDescription({
type: 'answer',
sdp: jsonMessage.sdpAnswer
})
this.#peerConnection.setRemoteDescription(answer)
}
5、添加远端iceCandidate
handleAddIceCandidate(jsonMessage) {
if (this.#peerConnection == null) {
return;
}
this.#peerConnection.addIceCandidate(jsonMessage.candidate)
}