BGMHandler.ts 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. /// <reference path="../Elements.ts" />
  2. module Elements.BGMHandler {
  3. var player = <HTMLAudioElement> document.getElementById("bgmPlayer");
  4. player.volume = 0.1;
  5. player.addEventListener("canplay", function () {
  6. this.play();
  7. this.style.display = "";
  8. });
  9. player.addEventListener("error", function () {
  10. this.style.display = "none";
  11. console.warn("Could not play the BGM ", this.src);
  12. });
  13. player.addEventListener("pause", function () {
  14. this.style.display = "none";
  15. });
  16. function getJsonFromUrl(url) : any {
  17. if(!url) url = location.search;
  18. var query = url.substr(1);
  19. var result = {};
  20. query.split("&").forEach(function(part) {
  21. var item = part.split("=");
  22. result[item[0]] = decodeURIComponent(item[1]);
  23. });
  24. return result;
  25. }
  26. export function playYT (vidID : string) {
  27. let proxyURL = "https://images" + (Math.floor(Math.random() * 33)) + "-focus-opensocial.googleusercontent.com/gadgets/proxy?container=none&url=";
  28. let vidInfo = encodeURIComponent("https://www.youtube.com/get_video_info?video_id=") + encodeURIComponent(vidID);
  29. fetch(proxyURL + vidInfo).then(response => {
  30. if (response.ok) {
  31. response.text().then((data : any) => {
  32. data = getJsonFromUrl(data);
  33. let streams = (data.url_encoded_fmt_stream_map + ',' + data.adaptive_fmts).split(',');
  34. let valid = [];
  35. for (let i = 0; i < streams.length; i++) {
  36. let stream = getJsonFromUrl(streams[i]);
  37. if (stream.type && stream.type.indexOf("audio") == 0) {
  38. valid.push(stream.url);
  39. }
  40. }
  41. // Last one has highest quality, if none found results "undefined" which just doesn't play
  42. player.src = valid.pop();
  43. });
  44. }
  45. });
  46. }
  47. /** TODO: Allow players to create a playlist of youtube URLs that vary with certain situations, then play one of those randomly every time situation arises
  48. e.g.: A list of songs for Combat, Exploration in the Forest, Talking with the Witch, etc.
  49. */
  50. }