H5实现webrtc流播放
admin 阅读: 2024-04-01
后台-插件-广告管理-内容页头部广告(手机) |
h5播放WebRTC,WebRTC(Web Real-Time Communication)是一种基于网页浏览器的开源项目,提供了实时音视频传输、数据共享等功能,现在各大浏览器已经逐渐加大对WebRTC技术的支持,实现WebRTC的视频推流,播放WebRTC流。
一、初始化连接
1、初始化WebRTC连接。主要涉及到获取本地媒体流、设置ICE服务器配置、创建PeerConnection对象等
this.pc = new RTCPeerConnection(null); this.pc.ontrack = (event) => { this._mediaElement['srcObject'] = event.streams[0]; }; this.pc.addTransceiver('audio', {direction: 'recvonly'}); this.pc.addTransceiver('video', {direction: 'recvonly'}); this.sendChannel = this.pc.createDataChannel('keepalive'); this.sendChannel.onclose = this.onChannelClose.bind(this); this.sendChannel.onopen = this.onChannelOpen.bind(this); this.sendChannel.onmessage = this.onChannelMessage.bind(this); this.pc.createOffer({ offerToReceiveVideo: !0, offerToReceiveAudio: !0 }).then((offer) => { return this.pc.setLocalDescription(offer).then(() => { return offer; }); }).then((offer) => { return new Promise((resolve, reject) => { this.HttpPost(url, window.btoa(offer.sdp)).then((res) => { resolve(res); }, function (rej) { reject(rej); }); }); }).then((answerSdp) => { return this.pc.setRemoteDescription(new RTCSessionDescription({ type: 'answer', sdp: window.atob(answerSdp) })); }).then(() => { this._isLoad = true; }).catch((reason) => { throw reason; });- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
2、ontrack回调中将媒体播放地址,绑定到video上。
3、createOffer方法,这个方法返回本地会话描述。
4、setLocalDescription方法。
5、需要先与服务端建立一个连接。HttpPost(),发送:offer.sdp 到推流端,服务端收到offer.sdp,再返回回来。
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
6、收到应答返回的offer.sdp, 设置为你的远端连接。
this.pc.setRemoteDescription(new RTCSessionDescription({ type: 'answer', sdp: window.atob(answerSdp) }));- 1
- 2
- 3
- 4
- 5
7、监听 sendChannel.onopen 连接是否建立成功。
8、前端播放的过程中需要与服务器通信保持连接,可以 sendChannel.send(msg)来保持持续拉流 。
9、服务器推流,前端开始播放。
二、完整代码
import PlayerEvents from '../FlvPlayer/flv.js/player/player-events'; import EventEmitter from 'events'; import * as common from '../common/common'; export default class WebRtcPlayer { constructor(url, options) { this.TAG = 'WebRtcPlayer'; this._type = 'WebRtcPlayer'; this._emitter = new EventEmitter(); // this.options = options || {}; this.pc = null; this._mediaElement = null; this.url = url; this.autoplay = !!options.autoplay || false; this.typeCallback = options.typeCallback; this.statusCallback = options.statusCallback; if (!url.match(/^webrtc?:\/\/||^webrtcs?:\/\//)) { throw ('JSWebrtc just work with webrtc'); } this.timer = null; this.sendChannel = null; this._mediaInfo = null; this._statisticsInfo = null; this.isPlaying = false; this._isLoad = false; this._isDestroy = false; this.e = { onvLoadedMetadata: this._onvLoadedMetadata.bind(this), onvSeeking: this._onvSeeking.bind(this), onvCanPlay: this._onvCanPlay.bind(this), onvPlay: this._onvPlay.bind(this), onvStalled: this._onvStalled.bind(this), onvProgress: this._onvProgress.bind(this), onvWaiting: this._onvWaiting.bind(this), onvPlaying: this._onvPlaying.bind(this) }; this.attachMediaElement(options.mediaElement, url); } on(event, listener) { if (event === PlayerEvents.MEDIA_INFO) { if (this._mediaInfo != null) { Promise.resolve().then(() => { this._emitter.emit(PlayerEvents.MEDIA_INFO, this.mediaInfo); }); } } else if (event === PlayerEvents.STATISTICS_INFO) { if (this._statisticsInfo != null) { Promise.resolve().then(() => { this._emitter.emit(PlayerEvents.STATISTICS_INFO, this.statisticsInfo); }); } } this._emitter.addListener(event, listener); } off(event, listener) { this._emitter.removeListener(event, listener); } attachMediaElement(mediaElement, url) { this._mediaElement = mediaElement; this._mediaElement = mediaElement; mediaElement.addEventListener('loadedmetadata', this.e.onvLoadedMetadata); mediaElement.addEventListener('seeking', this.e.onvSeeking); mediaElement.addEventListener('canplay', this.e.onvCanPlay); mediaElement.addEventListener('play', this.e.onvPlay); mediaElement.addEventListener('stalled', this.e.onvStalled); mediaElement.addEventListener('progress', this.e.onvProgress); mediaElement.addEventListener('waiting', this.e.onvWaiting); mediaElement.addEventListener('playing', this.e.onvPlaying); this.typeCallback(!false); this.load(url); } load(url) { this.statusCallback(0); if (this.pc) { this.pc.close(); } this.pc = new RTCPeerConnection(null); this.pc.ontrack = (event) => { this._mediaElement['srcObject'] = event.streams[0]; }; this.pc.addTransceiver('audio', {direction: 'recvonly'}); this.pc.addTransceiver('video', {direction: 'recvonly'}); this.sendChannel = this.pc.createDataChannel('keepalive'); this.sendChannel.onclose = this.onChannelClose.bind(this); this.sendChannel.onopen = this.onChannelOpen.bind(this); this.sendChannel.onmessage = this.onChannelMessage.bind(this); this.pc.createOffer({ offerToReceiveVideo: !0, offerToReceiveAudio: !0 }).then((offer) => { return this.pc.setLocalDescription(offer).then(() => { return offer; }); }).then((offer) => { return new Promise((resolve, reject) => { this.HttpPost(url, window.btoa(offer.sdp)).then((res) => { resolve(res); }, function (rej) { reject(rej); }); }); }).then((answerSdp) => { return this.pc.setRemoteDescription(new RTCSessionDescription({ type: 'answer', sdp: window.atob(answerSdp) })); }).then(() => { this._isLoad = true; }).catch((reason) => { throw reason; }); } onChannelClose() { clearInterval(this.timer); if (!this._isDestroy) { common.sleep(3000).then(() => { this.load(this.url); }); } } onChannelOpen() { this.timer = setInterval((() => { if (this.sendChannel) { this.sendChannel.send('ping'); } }), 3000); } onChannelMessage() { // console.log('onmessage'); } HttpPost(url, data) { return new Promise((resolve, reject) => { var xhr = new XMLHttpRequest(); xhr.onreadystatechange = () => { if (xhr.readyState === 4 && (xhr.status >= 200 && xhr.status < 300)) { var respone = xhr.responseText; xhr.onreadystatechange = new Function; xhr = null; resolve(respone); } }; xhr.open('POST', url.replace('webrtc', 'http'), true); xhr.send(data); }); } _onvLoadedMetadata() { } _onvSeeking() { } _onvCanPlay() { if (this.autoplay) { this._mediaElement.play(); } } _onvPlay() { this.isPlaying = true; this.statusCallback(100); } _onvStalled() { } _onvProgress() { } _onvWaiting() { } _onvPlaying() { } unload() { } play() { if (!this.isPlaying) { this._mediaElement.play(); this.isPlaying = true; } } pause() { if (this.isPlaying) { this._mediaElement.pause(); this.isPlaying = false; } } resume() { } openAudio() { } closeAudio() { } seek() { } stop() { this.destroy(); } destroy() { this._isDestroy = true; if (this.pc) { this.pc.close(); this.pc = null; } if (this._mediaElement) { this._mediaElement = null; } if (this.sendChannel) { this.sendChannel = null; } this.autoplay = null; this.typeCallback = null; this.statusCallback = null; this.isPlaying = false; this._isLoad = false; clearInterval(this.timer); } get isLoad() { return this._isLoad; } }- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
- 88
- 89
- 90
- 91
- 92
- 93
- 94
- 95
- 96
- 97
- 98
- 99
- 100
- 101
- 102
- 103
- 104
- 105
- 106
- 107
- 108
- 109
- 110
- 111
- 112
- 113
- 114
- 115
- 116
- 117
- 118
- 119
- 120
- 121
- 122
- 123
- 124
- 125
- 126
- 127
- 128
- 129
- 130
- 131
- 132
- 133
- 134
- 135
- 136
- 137
- 138
- 139
- 140
- 141
- 142
- 143
- 144
- 145
- 146
- 147
- 148
- 149
- 150
- 151
- 152
- 153
- 154
- 155
- 156
- 157
- 158
- 159
- 160
- 161
- 162
- 163
- 164
- 165
- 166
- 167
- 168
- 169
- 170
- 171
- 172
- 173
- 174
- 175
- 176
- 177
- 178
- 179
- 180
- 181
- 182
- 183
- 184
- 185
- 186
- 187
- 188
- 189
- 190
- 191
- 192
- 193
- 194
- 195
- 196
- 197
- 198
- 199
- 200
- 201
- 202
- 203
- 204
- 205
- 206
- 207
- 208
- 209
- 210
- 211
- 212
- 213
- 214
- 215
- 216
- 217
- 218
- 219
- 220
- 221
- 222
- 223
- 224
- 225
- 226
- 227
- 228
- 229
- 230
- 231
- 232
- 233
- 234
- 235
- 236
- 237
- 238
- 239
- 240
- 241
- 242
- 243
- 244
- 245
- 246
- 247
- 248
- 249
- 250
- 251
- 252
- 253
- 254
- 255
- 256
- 257
- 258
- 259
- 260
player-events.js
const PlayerEvents = { ERROR: 'error', LOADING_COMPLETE: 'loading_complete', RECOVERED_EARLY_EOF: 'recovered_early_eof', MEDIA_INFO: 'media_info', METADATA_ARRIVED: 'metadata_arrived', SCRIPTDATA_ARRIVED: 'scriptdata_arrived', STATISTICS_INFO: 'statistics_info' }; export default PlayerEvents;- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
common.js
export function sleep(ms) { return new Promise(resolve => setTimeout(resolve, ms)); }- 1
- 2
- 3
声明
1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。
在线投稿:投稿 站长QQ:1888636
后台-插件-广告管理-内容页尾部广告(手机) |