ajax.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. JSMpeg.Source.Ajax = (function(){ "use strict";
  2. var AjaxSource = function(url, options) {
  3. this.url = url;
  4. this.destination = null;
  5. this.request = null;
  6. this.streaming = false;
  7. this.completed = false;
  8. this.established = false;
  9. this.progress = 0;
  10. this.onEstablishedCallback = options.onSourceEstablished;
  11. this.onCompletedCallback = options.onSourceCompleted;
  12. };
  13. AjaxSource.prototype.connect = function(destination) {
  14. this.destination = destination;
  15. };
  16. AjaxSource.prototype.start = function() {
  17. this.request = new XMLHttpRequest();
  18. this.request.onreadystatechange = function() {
  19. if (
  20. this.request.readyState === this.request.DONE &&
  21. this.request.status === 200
  22. ) {
  23. this.onLoad(this.request.response);
  24. }
  25. }.bind(this);
  26. this.request.onprogress = this.onProgress.bind(this);
  27. this.request.open('GET', this.url);
  28. this.request.responseType = "arraybuffer";
  29. this.request.send();
  30. };
  31. AjaxSource.prototype.resume = function(secondsHeadroom) {
  32. // Nothing to do here
  33. };
  34. AjaxSource.prototype.destroy = function() {
  35. this.request.abort();
  36. };
  37. AjaxSource.prototype.onProgress = function(ev) {
  38. this.progress = (ev.loaded / ev.total);
  39. };
  40. AjaxSource.prototype.onLoad = function(data) {
  41. this.established = true;
  42. this.completed = true;
  43. this.progress = 1;
  44. if (this.onEstablishedCallback) {
  45. this.onEstablishedCallback(this);
  46. }
  47. if (this.onCompletedCallback) {
  48. this.onCompletedCallback(this);
  49. }
  50. if (this.destination) {
  51. this.destination.write(data);
  52. }
  53. };
  54. return AjaxSource;
  55. })();