useSoundcloudPlayer.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481
  1. import { ref, watch } from "vue";
  2. import utils from "@/utils";
  3. const soundcloudDomain = "https://w.soundcloud.com";
  4. export const useSoundcloudPlayer = () => {
  5. const uuid = utils.guid();
  6. const soundcloudIframeElement = ref();
  7. const widgetId = ref();
  8. const volume = ref();
  9. const readyCallback = ref();
  10. const attemptsToPlay = ref(0);
  11. const debouncePause = ref(null);
  12. const iframeUrl = ref("");
  13. const playAttemptTimeout = ref();
  14. const paused = ref(true);
  15. const currentTrackId = ref(null);
  16. const methodCallbacks = {};
  17. const eventListenerCallbacks = {};
  18. const stateChangeCallbacks = [];
  19. const debug = (...args) =>
  20. process.env.NODE_ENV === "development" &&
  21. console.debug("[USP]", uuid, widgetId.value, ...args);
  22. debug("Init start");
  23. if (!window.soundcloudIframeLockUuids)
  24. window.soundcloudIframeLockUuids = new Set();
  25. /*
  26. EVENTS:
  27. LOAD_PROGRESS: "loadProgress",
  28. PLAY_PROGRESS: "playProgress",
  29. PLAY: "play",
  30. PAUSE: "pause",
  31. FINISH: "finish",
  32. SEEK: "seek",
  33. READY: "ready",
  34. OPEN_SHARE_PANEL: "sharePanelOpened",
  35. CLICK_DOWNLOAD: "downloadClicked",
  36. CLICK_BUY: "buyClicked",
  37. ERROR: "error"
  38. METHODS:
  39. GET_VOLUME: "getVolume",
  40. GET_DURATION: "getDuration",
  41. GET_POSITION: "getPosition",
  42. GET_SOUNDS: "getSounds",
  43. GET_CURRENT_SOUND: "getCurrentSound",
  44. GET_CURRENT_SOUND_INDEX: "getCurrentSoundIndex",
  45. IS_PAUSED: "isPaused"
  46. PLAY: "play",
  47. PAUSE: "pause",
  48. TOGGLE: "toggle",
  49. SEEK_TO: "seekTo",
  50. SET_VOLUME: "setVolume",
  51. NEXT: "next",
  52. PREV: "prev",
  53. SKIP: "skip"
  54. REMOVE_LISTENER: "removeEventListener",
  55. ADD_LISTENER: "addEventListener"
  56. */
  57. const trackState = ref("NOT_PLAYING");
  58. const dispatchMessage = (method, value = null) => {
  59. const payload = {
  60. method,
  61. value
  62. };
  63. if (!soundcloudIframeElement.value) return;
  64. if (
  65. !soundcloudIframeElement.value.src ||
  66. !soundcloudIframeElement.value.src.startsWith(soundcloudDomain)
  67. )
  68. return;
  69. if (method !== "getPosition" && method !== "getDuration")
  70. debug("Dispatch message", method, value);
  71. soundcloudIframeElement.value.contentWindow.postMessage(
  72. JSON.stringify(payload),
  73. `${soundcloudDomain}/player`
  74. );
  75. };
  76. const onLoadListener = () => {};
  77. const onMessageListener = event => {
  78. if (event.origin !== soundcloudDomain) return;
  79. const data = JSON.parse(event.data);
  80. if (
  81. data.method !== "getPosition" &&
  82. data.method !== "getDuration" &&
  83. (data.method === "ready" || data.widgetId === widgetId.value)
  84. )
  85. debug("MESSAGE DATA", data);
  86. if (data.method === "ready") {
  87. if (window.soundcloudIframeLockUuid !== uuid) return;
  88. widgetId.value = data.widgetId;
  89. if (readyCallback.value) readyCallback.value();
  90. if (eventListenerCallbacks[data.method])
  91. eventListenerCallbacks[data.method].forEach(callback => {
  92. callback(data.value);
  93. });
  94. window.soundcloudIframeLockUuid = null;
  95. document.dispatchEvent(new Event("soundcloudUnlock"));
  96. return;
  97. }
  98. if (data.widgetId !== widgetId.value) return;
  99. if (methodCallbacks[data.method]) {
  100. methodCallbacks[data.method].forEach(callback => {
  101. callback(data.value);
  102. });
  103. methodCallbacks[data.method] = [];
  104. }
  105. if (eventListenerCallbacks[data.method]) {
  106. eventListenerCallbacks[data.method].forEach(callback => {
  107. callback(data.value);
  108. });
  109. }
  110. };
  111. const addMethodCallback = (type, cb) => {
  112. if (!methodCallbacks[type]) methodCallbacks[type] = [];
  113. methodCallbacks[type].push(cb);
  114. };
  115. const changeTrackState = newTrackState => {
  116. clearTimeout(debouncePause.value);
  117. const oldTrackState = trackState.value;
  118. trackState.value = newTrackState;
  119. if (newTrackState !== oldTrackState) {
  120. stateChangeCallbacks.forEach(cb => {
  121. cb(newTrackState);
  122. });
  123. }
  124. };
  125. const soundcloudGetIsPaused = callback => {
  126. let called = false;
  127. const _callback = value => {
  128. if (called) return;
  129. called = true;
  130. callback(value);
  131. };
  132. addMethodCallback("isPaused", _callback);
  133. dispatchMessage("isPaused");
  134. };
  135. const soundcloudGetCurrentSound = callback => {
  136. let called = false;
  137. const _callback = value => {
  138. if (called) return;
  139. called = true;
  140. callback(value);
  141. };
  142. addMethodCallback("getCurrentSound", _callback);
  143. dispatchMessage("getCurrentSound");
  144. };
  145. const attemptToPlay = () => {
  146. if (trackState.value === "playing") return;
  147. if (trackState.value !== "attempting_to_play") {
  148. attemptsToPlay.value = 0;
  149. changeTrackState("attempting_to_play");
  150. }
  151. attemptsToPlay.value += 1;
  152. dispatchMessage("play");
  153. setTimeout(() => {
  154. soundcloudGetIsPaused(value => {
  155. if (trackState.value !== "attempting_to_play") return;
  156. // Success
  157. if (!value) {
  158. changeTrackState("playing");
  159. return;
  160. }
  161. soundcloudGetCurrentSound(sound => {
  162. // Sound is not available to play
  163. if (
  164. value &&
  165. !paused.value &&
  166. typeof sound === "object" &&
  167. (!sound.playable ||
  168. !sound.public ||
  169. sound.policy === "BLOCK")
  170. ) {
  171. changeTrackState("sound_unavailable");
  172. attemptsToPlay.value = 0;
  173. return;
  174. }
  175. // Too many attempts, failed
  176. if (attemptsToPlay.value >= 10 && value && !paused.value) {
  177. changeTrackState("failed_to_play");
  178. attemptsToPlay.value = 0;
  179. return;
  180. }
  181. if (playAttemptTimeout.value)
  182. clearTimeout(playAttemptTimeout.value);
  183. playAttemptTimeout.value = setTimeout(() => {
  184. if (trackState.value === "attempting_to_play")
  185. attemptToPlay();
  186. }, 500);
  187. });
  188. });
  189. }, 500);
  190. };
  191. const changeIframeUrl = url => {
  192. iframeUrl.value = url;
  193. if (url && window.soundcloudIframeLockUuid !== uuid) {
  194. // Don't change the iframe src if the player hasn't initialized and isn't allowed to initialize yet
  195. if (url) window.soundcloudIframeLockUuids.add(uuid);
  196. if (!window.soundcloudIframeLockUuid)
  197. document.dispatchEvent(new Event("soundcloudUnlock"));
  198. return;
  199. }
  200. if (!url) widgetId.value = null;
  201. soundcloudIframeElement.value.setAttribute("src", url);
  202. };
  203. const documentUnlockEventListener = () => {
  204. if (
  205. !window.soundcloudIframeLockUuid &&
  206. window.soundcloudIframeLockUuids.size > 0 &&
  207. window.soundcloudIframeLockUuids.keys().next().value === uuid
  208. ) {
  209. window.soundcloudIframeLockUuid = uuid;
  210. window.soundcloudIframeLockUuids.delete(uuid);
  211. changeIframeUrl(iframeUrl.value);
  212. }
  213. };
  214. watch(soundcloudIframeElement, (newElement, oldElement) => {
  215. if (oldElement) {
  216. oldElement.removeEventListener("load", onLoadListener);
  217. window.removeEventListener("message", onMessageListener);
  218. if (window.soundcloudIframeLockUuid === uuid)
  219. window.soundcloudIframeLockUuid = null;
  220. window.soundcloudIframeLockUuids.delete(uuid);
  221. document.removeEventListener(
  222. "soundcloudUnlock",
  223. documentUnlockEventListener
  224. );
  225. }
  226. if (newElement) {
  227. newElement.addEventListener("load", onLoadListener);
  228. window.addEventListener("message", onMessageListener);
  229. document.removeEventListener(
  230. "soundcloudUnlock",
  231. documentUnlockEventListener
  232. );
  233. document.addEventListener(
  234. "soundcloudUnlock",
  235. documentUnlockEventListener
  236. );
  237. }
  238. if (!window.soundcloudIframeLockUuid)
  239. document.dispatchEvent(new Event("soundcloudUnlock"));
  240. });
  241. /* Exported functions */
  242. const soundcloudPlay = () => {
  243. paused.value = false;
  244. debug("Soundcloud play");
  245. if (trackState.value !== "attempting_to_play") attemptToPlay();
  246. };
  247. const soundcloudPause = () => {
  248. paused.value = true;
  249. debug("Soundcloud pause");
  250. if (playAttemptTimeout.value) clearTimeout(playAttemptTimeout.value);
  251. dispatchMessage("pause");
  252. };
  253. const soundcloudSetVolume = _volume => {
  254. volume.value = _volume;
  255. debug("Soundcloud set volume");
  256. dispatchMessage("setVolume", _volume);
  257. };
  258. const soundcloudSeekTo = time => {
  259. debug("SC SEEK TO", time);
  260. debug("Soundcloud seek to");
  261. dispatchMessage("seekTo", time);
  262. };
  263. const soundcloudGetPosition = callback => {
  264. let called = false;
  265. const _callback = value => {
  266. if (called) return;
  267. called = true;
  268. callback(value);
  269. };
  270. addMethodCallback("getPosition", _callback);
  271. dispatchMessage("getPosition");
  272. };
  273. const soundcloudGetDuration = callback => {
  274. let called = false;
  275. const _callback = value => {
  276. if (called) return;
  277. called = true;
  278. callback(value);
  279. };
  280. addMethodCallback("getDuration", _callback);
  281. dispatchMessage("getDuration");
  282. };
  283. const soundcloudGetState = () => trackState.value;
  284. const soundcloudGetTrackId = () => currentTrackId.value;
  285. const soundcloudGetTrackState = () => trackState.value;
  286. const soundcloudLoadTrack = (trackId, startTime, _paused) => {
  287. if (!soundcloudIframeElement.value) return;
  288. debug("Soundcloud load track");
  289. const url = `${soundcloudDomain}/player?autoplay=false&buying=false&sharing=false&download=false&show_artwork=false&show_playcount=false&show_user=false&url=${`https://api.soundcloud.com/tracks/${trackId}`}`;
  290. changeIframeUrl(url);
  291. paused.value = _paused;
  292. currentTrackId.value = trackId;
  293. if (playAttemptTimeout.value) clearTimeout(playAttemptTimeout.value);
  294. changeTrackState("not_started");
  295. readyCallback.value = () => {
  296. Object.keys(eventListenerCallbacks).forEach(event => {
  297. dispatchMessage("addEventListener", event);
  298. });
  299. dispatchMessage("setVolume", volume.value ?? 20);
  300. dispatchMessage("seekTo", (startTime ?? 0) * 1000);
  301. if (!_paused) attemptToPlay();
  302. };
  303. };
  304. const soundcloudBindListener = (name, callback) => {
  305. if (!eventListenerCallbacks[name]) {
  306. eventListenerCallbacks[name] = [];
  307. dispatchMessage("addEventListener", name);
  308. }
  309. eventListenerCallbacks[name].push(callback);
  310. };
  311. const soundcloudOnTrackStateChange = callback => {
  312. debug("On track state change listener added");
  313. stateChangeCallbacks.push(callback);
  314. };
  315. const soundcloudDestroy = () => {
  316. if (!soundcloudIframeElement.value) return;
  317. changeIframeUrl(null);
  318. currentTrackId.value = null;
  319. changeTrackState("none");
  320. };
  321. const soundcloudUnload = () => {
  322. window.removeEventListener("message", onMessageListener);
  323. };
  324. soundcloudBindListener("play", () => {
  325. debug("On play");
  326. if (trackState.value !== "attempting_to_play")
  327. changeTrackState("playing");
  328. });
  329. soundcloudBindListener("pause", eventValue => {
  330. debug("On pause", eventValue);
  331. const finishedPlaying = eventValue.relativePosition === 1;
  332. if (finishedPlaying) return;
  333. clearTimeout(debouncePause.value);
  334. debouncePause.value = setTimeout(() => {
  335. if (trackState.value !== "attempting_to_play")
  336. changeTrackState("paused");
  337. }, 500);
  338. });
  339. soundcloudBindListener("finish", () => {
  340. debug("On finish");
  341. changeTrackState("finished");
  342. });
  343. soundcloudBindListener("error", () => {
  344. debug("On error");
  345. changeTrackState("error");
  346. });
  347. debug("Init end");
  348. return {
  349. soundcloudIframeElement,
  350. soundcloudPlay,
  351. soundcloudPause,
  352. soundcloudSeekTo,
  353. soundcloudSetVolume,
  354. soundcloudLoadTrack,
  355. soundcloudGetPosition,
  356. soundcloudGetDuration,
  357. soundcloudGetIsPaused,
  358. soundcloudGetState,
  359. soundcloudGetTrackId,
  360. soundcloudGetCurrentSound,
  361. soundcloudGetTrackState,
  362. soundcloudBindListener,
  363. soundcloudOnTrackStateChange,
  364. soundcloudDestroy,
  365. soundcloudUnload
  366. };
  367. };