useSoundcloudPlayer.ts 8.8 KB

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