srsRtc.js 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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. this.pc && this.pc.close();
  18. this.pc = null;
  19. }
  20. async getVideo(clipUrl){
  21. if(!this.pc){
  22. this.pc = new RTCPeerConnection(null);
  23. this.pc.ontrack = (event) => {
  24. // https://webrtc.org/getting-started/remote-streams
  25. console.log('event',event.track)
  26. if(this.stream){
  27. // this.stream.removeTrack(event.track));
  28. const videoTrack = this.stream.getVideoTracks().find(i=>i.kind ==='video')
  29. console.log('videoTrack',videoTrack)
  30. if(videoTrack){
  31. this.stream.removeTrack(videoTrack);
  32. }
  33. // if(this.stream.removeTrack())
  34. this.stream.addTrack(event.track);
  35. }
  36. };
  37. }
  38. this.pc.addTransceiver("video", {direction: "recvonly"});
  39. const serverApi ='https://demo-kms.4dage.com:443/rtc/v1/play/';
  40. const tid = Number(parseInt(new Date().getTime()*Math.random()*100)).toString(16).slice(0, 7);
  41. var offer = await this.pc.createOffer();
  42. this.offer = offer;
  43. await this.pc.setLocalDescription(offer);
  44. const session = await new Promise(function(resolve, reject) {
  45. // @see https://github.com/rtcdn/rtcdn-draft
  46. var data = {
  47. api: serverApi,
  48. tid: tid,
  49. streamurl: clipUrl,
  50. clientip: null,
  51. sdp: offer.sdp
  52. };
  53. console.log("Generated offer: ", data);
  54. $.ajax({
  55. type: "POST", url: serverApi, data: JSON.stringify(data),
  56. contentType:'application/json', dataType: 'json'
  57. }).done(function(data) {
  58. console.log("Got answer: ", data);
  59. if (data.code) {
  60. reject(data); return;
  61. }
  62. resolve(data);
  63. }).fail(function(reason){
  64. reject(reason);
  65. });
  66. });
  67. await this.pc.setRemoteDescription(
  68. new RTCSessionDescription({type: 'answer', sdp: session.sdp})
  69. );
  70. return session;
  71. }
  72. }