srsRtc.js 3.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. export class SrsRTC {
  2. constructor(url){
  3. this.stream = new MediaStream();
  4. this.url = url;
  5. this.offer = null;
  6. this.pc =null;
  7. // this.pc = new RTCPeerConnection(null);
  8. // this.pc.ontrack = (event) => {
  9. // // https://webrtc.org/getting-started/remote-streams
  10. // console.warn('event',event.track)
  11. // if(this.stream){
  12. // this.stream.addTrack(event.track);
  13. // }
  14. // };
  15. }
  16. close(){
  17. var remoteVideo = document.querySelector("#testVideoFeed");
  18. if(remoteVideo.srcObject){
  19. remoteVideo.srcObject.getTracks().forEach(track => track.stop());
  20. }
  21. this.pc && this.pc.close();
  22. this.pc = null;
  23. }
  24. async getVideo(clipUrl){
  25. if(!this.pc){
  26. this.pc = new RTCPeerConnection(null);
  27. this.pc.ontrack = (event) => {
  28. // https://webrtc.org/getting-started/remote-streams
  29. console.log('event',event)
  30. if(this.stream){
  31. // this.stream.removeTrack(event.track));
  32. const videoTrack = this.stream.getVideoTracks().find(i=>i.kind ==='video')
  33. console.log('旧videoTrack',videoTrack)
  34. if(videoTrack){
  35. this.stream.removeTrack(videoTrack);
  36. }
  37. // if(this.stream.removeTrack())
  38. this.stream.addTrack(event.track);
  39. }
  40. // mediaRecorder.
  41. };
  42. this.pc.ondatachannel =(data)=>{
  43. console.log('data',data)
  44. }
  45. this.pc.onaddstream = function (obj) {
  46. console.error(obj)
  47. }
  48. }
  49. this.pc.addTransceiver("video", {direction: "recvonly"});
  50. const serverApi ='https://demo-kms.4dage.com:443/rtc/v1/play/';
  51. const tid = Number(parseInt(new Date().getTime()*Math.random()*100)).toString(16).slice(0, 7);
  52. var offer = await this.pc.createOffer();
  53. this.offer = offer;
  54. await this.pc.setLocalDescription(offer);
  55. const session = await new Promise(function(resolve, reject) {
  56. // @see https://github.com/rtcdn/rtcdn-draft
  57. var data = {
  58. api: serverApi,
  59. tid: tid,
  60. streamurl: clipUrl,
  61. clientip: null,
  62. sdp: offer.sdp
  63. };
  64. console.log("Generated offer: ", data);
  65. $.ajax({
  66. type: "POST", url: serverApi, data: JSON.stringify(data),
  67. contentType:'application/json', dataType: 'json'
  68. }).done(function(data) {
  69. console.log("Got answer: ", data);
  70. if (data.code) {
  71. reject(data); return;
  72. }
  73. resolve(data);
  74. }).fail(function(reason){
  75. reject(reason);
  76. });
  77. });
  78. await this.pc.setRemoteDescription(
  79. new RTCSessionDescription({type: 'answer', sdp: session.sdp})
  80. );
  81. return session;
  82. }
  83. }