useSoundcloudPlayer.ts 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  1. import { ref, watch } from "vue";
  2. const TAG = "[USP]";
  3. const soundcloudDomain = "https://w.soundcloud.com";
  4. export const useSoundcloudPlayer = () => {
  5. console.debug(TAG, "Init start");
  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 playAttemptTimeout = ref();
  13. const paused = ref(true);
  14. const currentTrackId = ref(null);
  15. const methodCallbacks = {};
  16. const eventListenerCallbacks = {};
  17. const stateChangeCallbacks = [];
  18. /*
  19. EVENTS:
  20. LOAD_PROGRESS: "loadProgress",
  21. PLAY_PROGRESS: "playProgress",
  22. PLAY: "play",
  23. PAUSE: "pause",
  24. FINISH: "finish",
  25. SEEK: "seek",
  26. READY: "ready",
  27. OPEN_SHARE_PANEL: "sharePanelOpened",
  28. CLICK_DOWNLOAD: "downloadClicked",
  29. CLICK_BUY: "buyClicked",
  30. ERROR: "error"
  31. METHODS:
  32. GET_VOLUME: "getVolume",
  33. GET_DURATION: "getDuration",
  34. GET_POSITION: "getPosition",
  35. GET_SOUNDS: "getSounds",
  36. GET_CURRENT_SOUND: "getCurrentSound",
  37. GET_CURRENT_SOUND_INDEX: "getCurrentSoundIndex",
  38. IS_PAUSED: "isPaused"
  39. PLAY: "play",
  40. PAUSE: "pause",
  41. TOGGLE: "toggle",
  42. SEEK_TO: "seekTo",
  43. SET_VOLUME: "setVolume",
  44. NEXT: "next",
  45. PREV: "prev",
  46. SKIP: "skip"
  47. REMOVE_LISTENER: "removeEventListener",
  48. ADD_LISTENER: "addEventListener"
  49. */
  50. const trackState = ref("NOT_PLAYING");
  51. const dispatchMessage = (method, value = null) => {
  52. const payload = {
  53. method,
  54. value
  55. };
  56. if (!soundcloudIframeElement.value) return;
  57. if (
  58. !soundcloudIframeElement.value.src ||
  59. !soundcloudIframeElement.value.src.startsWith(soundcloudDomain)
  60. )
  61. return;
  62. if (method !== "getPosition" && method !== "getDuration")
  63. console.debug(TAG, "Dispatch message", method, value);
  64. soundcloudIframeElement.value.contentWindow.postMessage(
  65. JSON.stringify(payload),
  66. `${soundcloudDomain}/player`
  67. );
  68. };
  69. const onLoadListener = () => {};
  70. const onMessageListener = event => {
  71. if (event.origin !== soundcloudDomain) return;
  72. const data = JSON.parse(event.data);
  73. if (data.method !== "getPosition" && data.method !== "getDuration")
  74. console.log("MESSAGE DATA", data);
  75. if (data.method === "ready") {
  76. widgetId.value = data.widgetId;
  77. if (!readyCallback.value) return;
  78. readyCallback.value();
  79. return;
  80. }
  81. if (methodCallbacks[data.method]) {
  82. methodCallbacks[data.method].forEach(callback => {
  83. callback(data.value);
  84. });
  85. methodCallbacks[data.method] = [];
  86. }
  87. if (eventListenerCallbacks[data.method]) {
  88. eventListenerCallbacks[data.method].forEach(callback => {
  89. callback(data.value);
  90. });
  91. }
  92. };
  93. const addMethodCallback = (type, cb) => {
  94. if (!methodCallbacks[type]) methodCallbacks[type] = [];
  95. methodCallbacks[type].push(cb);
  96. };
  97. const changeTrackState = newTrackState => {
  98. clearTimeout(debouncePause.value);
  99. const oldTrackState = trackState.value;
  100. trackState.value = newTrackState;
  101. if (newTrackState !== oldTrackState) {
  102. stateChangeCallbacks.forEach(cb => {
  103. cb(newTrackState);
  104. });
  105. }
  106. };
  107. const soundcloudGetIsPaused = callback => {
  108. let called = false;
  109. const _callback = value => {
  110. if (called) return;
  111. called = true;
  112. callback(value);
  113. };
  114. addMethodCallback("isPaused", _callback);
  115. dispatchMessage("isPaused");
  116. };
  117. const attemptToPlay = () => {
  118. if (trackState.value === "playing") return;
  119. if (trackState.value !== "attempting_to_play") {
  120. attemptsToPlay.value = 0;
  121. changeTrackState("attempting_to_play");
  122. }
  123. attemptsToPlay.value += 1;
  124. dispatchMessage("play");
  125. setTimeout(() => {
  126. soundcloudGetIsPaused(value => {
  127. if (trackState.value !== "attempting_to_play") return;
  128. // Success
  129. if (!value) {
  130. changeTrackState("playing");
  131. return;
  132. }
  133. // Too many attempts, failed
  134. if (attemptsToPlay.value >= 10 && value && !paused.value) {
  135. changeTrackState("failed_to_play");
  136. attemptsToPlay.value = 0;
  137. return;
  138. }
  139. if (playAttemptTimeout.value)
  140. clearTimeout(playAttemptTimeout.value);
  141. playAttemptTimeout.value = setTimeout(() => {
  142. if (trackState.value === "attempting_to_play")
  143. attemptToPlay();
  144. }, 500);
  145. });
  146. }, 500);
  147. };
  148. watch(soundcloudIframeElement, (newElement, oldElement) => {
  149. if (oldElement) {
  150. oldElement.removeEventListener("load", onLoadListener);
  151. window.removeEventListener("message", onMessageListener);
  152. }
  153. if (newElement) {
  154. newElement.addEventListener("load", onLoadListener);
  155. window.addEventListener("message", onMessageListener);
  156. }
  157. });
  158. /* Exported functions */
  159. const soundcloudPlay = () => {
  160. paused.value = false;
  161. console.debug(TAG, "Soundcloud play");
  162. if (trackState.value !== "attempting_to_play") attemptToPlay();
  163. };
  164. const soundcloudPause = () => {
  165. paused.value = true;
  166. console.debug(TAG, "Soundcloud pause");
  167. if (playAttemptTimeout.value) clearTimeout(playAttemptTimeout.value);
  168. dispatchMessage("pause");
  169. };
  170. const soundcloudSetVolume = _volume => {
  171. volume.value = _volume;
  172. console.debug(TAG, "Soundcloud set volume");
  173. dispatchMessage("setVolume", _volume);
  174. };
  175. const soundcloudSeekTo = time => {
  176. console.log("SC SEEK TO", time);
  177. console.debug(TAG, "Soundcloud seek to");
  178. dispatchMessage("seekTo", time);
  179. };
  180. const soundcloudGetPosition = callback => {
  181. let called = false;
  182. const _callback = value => {
  183. if (called) return;
  184. called = true;
  185. callback(value);
  186. };
  187. addMethodCallback("getPosition", _callback);
  188. dispatchMessage("getPosition");
  189. };
  190. const soundcloudGetDuration = callback => {
  191. let called = false;
  192. const _callback = value => {
  193. if (called) return;
  194. called = true;
  195. callback(value);
  196. };
  197. addMethodCallback("getDuration", _callback);
  198. dispatchMessage("getDuration");
  199. };
  200. const soundcloudGetState = () => trackState.value;
  201. const soundcloudGetCurrentSound = callback => {
  202. let called = false;
  203. const _callback = value => {
  204. if (called) return;
  205. called = true;
  206. callback(value);
  207. };
  208. addMethodCallback("getCurrentSound", _callback);
  209. dispatchMessage("getCurrentSound");
  210. };
  211. const soundcloudGetTrackId = () => currentTrackId.value;
  212. const soundcloudLoadTrack = (trackId, startTime, _paused) => {
  213. if (!soundcloudIframeElement.value) return;
  214. console.debug(TAG, "Soundcloud load track");
  215. 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}`}`;
  216. soundcloudIframeElement.value.setAttribute("src", url);
  217. paused.value = _paused;
  218. currentTrackId.value = trackId;
  219. if (playAttemptTimeout.value) clearTimeout(playAttemptTimeout.value);
  220. changeTrackState("not_started");
  221. readyCallback.value = () => {
  222. Object.keys(eventListenerCallbacks).forEach(event => {
  223. dispatchMessage("addEventListener", event);
  224. });
  225. dispatchMessage("setVolume", volume.value ?? 20);
  226. dispatchMessage("seekTo", (startTime ?? 0) * 1000);
  227. if (!_paused) attemptToPlay();
  228. };
  229. };
  230. const soundcloudBindListener = (name, callback) => {
  231. if (!eventListenerCallbacks[name]) {
  232. eventListenerCallbacks[name] = [];
  233. dispatchMessage("addEventListener", name);
  234. }
  235. eventListenerCallbacks[name].push(callback);
  236. };
  237. const soundcloudOnTrackStateChange = callback => {
  238. console.debug(TAG, "On track state change listener added");
  239. stateChangeCallbacks.push(callback);
  240. };
  241. const soundcloudDestroy = () => {
  242. if (!soundcloudIframeElement.value) return;
  243. 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/${0}`}`;
  244. soundcloudIframeElement.value.setAttribute("src", url);
  245. currentTrackId.value = null;
  246. changeTrackState("none");
  247. };
  248. const soundcloudUnload = () => {
  249. window.removeEventListener("message", onMessageListener);
  250. };
  251. soundcloudBindListener("play", () => {
  252. console.debug(TAG, "On play");
  253. if (trackState.value !== "attempting_to_play")
  254. changeTrackState("playing");
  255. });
  256. soundcloudBindListener("pause", eventValue => {
  257. console.debug(TAG, "On pause", eventValue);
  258. const finishedPlaying = eventValue.relativePosition === 1;
  259. if (finishedPlaying) return;
  260. clearTimeout(debouncePause.value);
  261. debouncePause.value = setTimeout(() => {
  262. if (trackState.value !== "attempting_to_play")
  263. changeTrackState("paused");
  264. }, 500);
  265. });
  266. soundcloudBindListener("finish", () => {
  267. console.debug(TAG, "On finish");
  268. changeTrackState("finished");
  269. });
  270. soundcloudBindListener("error", () => {
  271. console.debug(TAG, "On error");
  272. changeTrackState("error");
  273. });
  274. console.debug(TAG, "Init end");
  275. return {
  276. soundcloudIframeElement,
  277. soundcloudPlay,
  278. soundcloudPause,
  279. soundcloudSeekTo,
  280. soundcloudSetVolume,
  281. soundcloudLoadTrack,
  282. soundcloudGetPosition,
  283. soundcloudGetDuration,
  284. soundcloudGetIsPaused,
  285. soundcloudGetState,
  286. soundcloudGetTrackId,
  287. soundcloudGetCurrentSound,
  288. soundcloudBindListener,
  289. soundcloudOnTrackStateChange,
  290. soundcloudDestroy,
  291. soundcloudUnload
  292. };
  293. };