srsRtc.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. export class SrsRTC {
  2. constructor(url){
  3. this.pc = new RTCPeerConnection(null);
  4. this.stream = new MediaStream();
  5. this.url = url;
  6. this.pc.ontrack = (event) => {
  7. // https://webrtc.org/getting-started/remote-streams
  8. console.log('event',event.track)
  9. if(this.stream){
  10. this.stream.addTrack(event.track);
  11. }
  12. };
  13. }
  14. async getVideo(clipUrl){
  15. this.pc.addTransceiver("video", {direction: "recvonly"});
  16. const serverApi ='https://demo-kms.4dage.com:443/rtc/v1/play/';
  17. const tid = Number(parseInt(new Date().getTime()*Math.random()*100)).toString(16).slice(0, 7);
  18. var offer = await this.pc.createOffer();
  19. await this.pc.setLocalDescription(offer);
  20. const session = await new Promise(function(resolve, reject) {
  21. // @see https://github.com/rtcdn/rtcdn-draft
  22. var data = {
  23. api: serverApi,
  24. tid: tid,
  25. streamurl: clipUrl,
  26. clientip: null,
  27. sdp: offer.sdp
  28. };
  29. console.log("Generated offer: ", data);
  30. $.ajax({
  31. type: "POST", url: serverApi, data: JSON.stringify(data),
  32. contentType:'application/json', dataType: 'json'
  33. }).done(function(data) {
  34. console.log("Got answer: ", data);
  35. if (data.code) {
  36. reject(data); return;
  37. }
  38. resolve(data);
  39. }).fail(function(reason){
  40. reject(reason);
  41. });
  42. });
  43. await this.pc.setRemoteDescription(
  44. new RTCSessionDescription({type: 'answer', sdp: session.sdp})
  45. );
  46. return session;
  47. }
  48. }