赞
踩
目前google chrome 已经原生支持webrtc了,做低延迟播放的小伙伴们有福了。目前已经有淘宝在售支持webrtc的摄像头。超低延迟播放视频不再是难事了。
网页访问代码
- function initRtcPeerConnection(streamPath) {
- rtcLoading = true;
- var rtcPeerConnection = new RTCPeerConnection({
- iceServers: [
- {
- urls: 'stun:stun.cloud.xstrive.com:3478'
- },
- ]
- });
- rtcPeerConnection.addTransceiver('video', {
- direction: "recvonly"
- });
- rtcPeerConnection.addTransceiver('audio',{
- direction:'recvonly'
- });
- rtcPeerConnection.onsignalingstatechange = e => {
- // console.log('onsignalingstatechange', e);
- };
- rtcPeerConnection.oniceconnectionstatechange = e => {
- console.log('oniceconnectionstatechange', rtcPeerConnection.iceConnectionState);
- };
- var iceGatheringState = false
- rtcPeerConnection.onicecandidate = event => {
- if (rtcPeerConnection.iceGatheringState === "complete") {
- iceGatheringState = true
- // console.log("onicecandidate iceGatheringState: ", rtcPeerConnection.iceGatheringState)
- }
- };
- rtcPeerConnection.ontrack = event => {
- // console.log('ontrack', event);
- document.getElementById('player').srcObject = event.streams[0];
- };
- rtcPeerConnection.createOffer().then((ret)=> {
- rtcPeerConnection.setLocalDescription(ret).finally(()=> {
- var i1 = 0
- var inter = setInterval(()=> {
- i1 += 1;
- if (iceGatheringState || i1 > 200) {
- clearInterval(inter)
- reqFetch(rtcPeerConnection, streamPath)
- }
- }, 20)
- })
- });
- rtcPeerConn = rtcPeerConnection
- }
- function reqFetch(rtcPeerConnection, streamPath) {
- var data = {
- sdp: rtcPeerConnection.localDescription.sdp,
- type: rtcPeerConnection.localDescription.type,
- }
- $.ajax({
- type:"POST",
- url:"/api/webrtc/play?streamPath=" + streamPath,
- data: JSON.stringify(data),
- contentType: "text/plain",
- success: function(data){
- rtcLoading = false
- var result = data;
- if (result.code) {
- rtcPeerConnection.close();
- alert(result.msg)
- return;
- }
- rtcPeerConnection.setRemoteDescription(new RTCSessionDescription({ sdp: result.sdp, type: 'answer' })).catch((ret)=> {
- console.log("setRemoteDescription catch:", ret)
- alert("播放失败,请稍后尝试")
- });
- },
- error: function () {
- rtcLoading = false
- rtcPeerConnection.close();
- }
- })
- }
-
- function showPlay() {
- // 显示遮罩
- $('.mask').css('display','block');
- initRtcPeerConnection("hlsram/live0")
- }
-
- function closePlayer() {
- // 暂时视频
- if(rtcPeerConn){
- rtcPeerConn.close();
- rtcPeerConn = null;
- }
- var py = document.getElementById('player');
- if (py) {
- py.srcObject = null
- }
-
- // 关闭遮罩
- $('.mask').css('display','none');
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。