Openverse is a search engine for openly-licensed media. This monorepo includes all application code.
Fix global audio syncing and seeking issues (#654)
sarayourfriendc13125e9ed72
diff --git a/src/components/VAudioTrack/VAudioTrack.vue b/src/components/VAudioTrack/VAudioTrack.vueindex 4d0fde387..8915e850a 100644--- a/src/components/VAudioTrack/VAudioTrack.vue+++ b/src/components/VAudioTrack/VAudioTrack.vue@@ -33,10 +33,13 @@ import {defineComponent,ref,useStore,- onMounted,watch,+ onUnmounted,+ useRoute,} from '@nuxtjs/composition-api'+import { useActiveAudio } from '~/composables/use-active-audio'+import VPlayPause from '~/components/VAudioTrack/VPlayPause.vue'import VWaveform from '~/components/VAudioTrack/VWaveform.vue'@@ -45,12 +48,52 @@ import VRowLayout from '~/components/VAudioTrack/layouts/VRowLayout.vue'import VBoxLayout from '~/components/VAudioTrack/layouts/VBoxLayout.vue'import VGlobalLayout from '~/components/VAudioTrack/layouts/VGlobalLayout.vue'-import { ACTIVE } from '~/constants/store-modules'+import { ACTIVE, MEDIA } from '~/constants/store-modules'import {PAUSE_ACTIVE_MEDIA_ITEM,SET_ACTIVE_MEDIA_ITEM,} from '~/constants/mutation-types'+const propTypes = {+ /**+ * the information about the track, typically from a track's detail endpoint+ */+ audio: {+ type: /** @type {import('@nuxtjs/composition-api').PropType<import('~/store/types').AudioDetail>} */ (+ Object+ ),+ required: /** @type {true} */ (true),+ },+ /**+ * the arrangement of the contents on the canvas; This determines the+ * overall L&F of the audio component.+ */+ layout: {+ type: /** @type {import('@nuxtjs/composition-api').PropType<'full' | 'box' | 'row' | 'global'>} */ (+ String+ ),+ default: 'full',+ /**+ * @param {string} val+ */+ validator: (val) => ['full', 'box', 'row', 'global'].includes(val),+ },+ /**+ * the size of the component; Both 'box' and 'row' layouts offer multiple+ * sizes to choose from.+ */+ size: {+ type: /** @type {import('@nuxtjs/composition-api').PropType<'s' | 'm' | 'l'>} */ (+ String+ ),+ default: 'm',+ /**+ * @param {string} val+ */+ validator: (val) => ['s', 'm', 'l'].includes(val),+ },+}+/*** Displays the waveform and basic information about the track, along with* controls to play, pause or seek to a point on the track.@@ -67,200 +110,195 @@ export default defineComponent({VBoxLayout,VGlobalLayout,},- props: {- /**- * the information about the track, typically from a track's detail endpoint- */- audio: {- type: Object,- required: true,- },- /**- * the arrangement of the contents on the canvas; This determines the- * overall L&F of the audio component.- */- layout: {- type: String,- default: 'full',- validator: (val) => ['full', 'box', 'row', 'global'].includes(val),- },- /**- * the size of the component; Both 'box' and 'row' layouts offer multiple- * sizes to choose from.- */- size: {- type: String,- default: 'm',- validator: (val) => ['s', 'm', 'l'].includes(val),- },- },+ props: propTypes,+ /**+ * @param {import('@nuxtjs/composition-api').ExtractPropTypes<typeof propTypes>} props+ */setup(props) {const store = useStore()+ const route = useRoute()- /* Local status */+ const activeAudio = useActiveAudio()const status = ref('paused')- /**- * Set the local status to 'playing' and start measuring the current time.- */- const localPlay = () => {- status.value = 'playing'- updateTimeLoop()- }- /**- * Set the local status to 'paused'.- */- const localPause = () => {- status.value = 'paused'- }- onMounted(() => {- if (isActiveTrack.value && store.state.active.status === 'playing') {- localPlay()- } else {- localPause()- }- })+ const currentTime = ref(0)- /* Timekeeping */+ const initLocalAudio = () => {+ // Preserve existing local audio if we plucked it from the global active audio+ if (!localAudio) localAudio = new Audio(props.audio.url)- const currentTime = ref(0) // seconds- const duration = computed(() => (props.audio.duration ?? 0) / 1e3) // seconds+ localAudio.addEventListener('play', setPlaying)+ localAudio.addEventListener('pause', setPaused)+ localAudio.addEventListener('ended', setPlayed)+ localAudio.addEventListener('timeupdate', setTimeWhenPaused)- const updateTime = () => {- if (- window?.audioEl &&- /**- * When the user switches from playing one audio track to another,- * say on the related audio section, if we don't check that the src- * of the audio element matches the source of the audio for this- * current instance of the audio track component, then we'll end up- * updating this instances `currentTime` ref to the value of the- * current time of the audio playing for the other element.- *- * The effect of this is that when you're switching audio tracks that- * are playing, the previous track that was playing will end up having- * it's current time set to the current time of the next audio track.- */- window.audioEl.src === props.audio.url- ) {- currentTime.value = window.audioEl.currentTime- if (currentTime.value >= duration.value) {- store.commit(`${ACTIVE}/${PAUSE_ACTIVE_MEDIA_ITEM}`)- status.value = 'played'+ /**+ * Similar to the behavior in the global audio track,+ * if the local audio was set to an already existing and+ * matching active global track, then we'll need to initialize+ * the status based on the `paused` and `ended` booleans+ * on the audio object.+ *+ * For newly initialized audio objects, this is harmless,+ * but it is essential for making sure page transitions+ * preserve the existing, already manipulated audio+ * object's state.+ *+ * Unlike the global audio track, however, this will not+ * always result in a status of `playing` in practice,+ * as the state of the active global track could be any+ * of the three statuses we track when the page transition+ * happens. For example, the audio track on the result page+ * could have been played through (and thus `ended`), or it+ * could be paused mid-way (and thus `paused`), or neither+ * and thus would be playing.+ */+ if (localAudio.paused) {+ if (localAudio.ended) {+ setPlayed()+ } else {+ setPaused()}+ } else {+ setPlaying()}++ currentTime.value = localAudio.currentTime}+ /**+ * We can only create the local audio object on the client,+ * so the initialization of this variable is hidden inside+ * the `initLocalAudio` function which is only called when+ * playback is first requested or when the track if first seeked.+ *+ * However, when navigating to an audio result page, if+ * the globally active audio already matches the result+ * that was clicked on, hijack that object instead and+ * treat it as the local audio for this instance.+ *+ * @type {HTMLAudioElement | undefined}+ * */+ let localAudio =+ activeAudio.obj.value?.src === props.audio.url+ ? activeAudio.obj.value+ : undefined+const updateTimeLoop = () => {- updateTime()- if (status.value === 'playing') {- // Audio is playing, keep looping+ if (localAudio && status.value === 'playing') {+ currentTime.value = localAudio.currentTimewindow.requestAnimationFrame(updateTimeLoop)- } else {- // Update time one last time on the next frame to try to fix- // some weird, difficult to reproduce, seemingly machine- // dependent bugs, described in the PR discussion below:- // https://github.com/WordPress/openverse-frontend/pull/633- window.requestAnimationFrame(updateTime)}}- /* Interface with active media store */-- const isActiveTrack = computed(- () =>- store.state.active.type === 'audio' &&- store.state.active.id === props.audio.id- )- const message = computed(() => store.state.active.message)-- /**- * Plays the audio using the `HTMLAudioElement`.- */- const elPlay = () => {- if (window?.audioEl) {- if (window.audioEl.src !== props.audio.url) {- window.audioEl.src = props.audio.url- // Set the current time of the audio back to the seeked time- // of the waveform/timeline. In the future we might change- // this to reset the audio back to 0 anytime another audio- // is played but for now this is simpler and requires less- // cross-instance communication.- window.audioEl.currentTime = currentTime.value+ const setPlaying = () => {+ status.value = 'playing'+ activeAudio.obj.value = localAudio+ store.commit(`${ACTIVE}/${SET_ACTIVE_MEDIA_ITEM}`, {+ type: 'audio',+ id: props.audio.id,+ })+ updateTimeLoop()+ }+ const setPaused = () => {+ status.value = 'paused'+ store.commit(`${ACTIVE}/${PAUSE_ACTIVE_MEDIA_ITEM}`)+ }+ const setPlayed = () => (status.value = 'played')+ const setTimeWhenPaused = () => {+ if (status.value !== 'playing' && localAudio) {+ currentTime.value = localAudio.currentTime+ if (status.value === 'played') {+ // Set to pause to remove replay icon+ status.value = 'paused'}- window.audioEl.play()}}+/**- * Pauses the audio using the `HTMLAudioElement` and updates local state.+ * If we're transforming the globally active audio+ * into our local audio, then we need to initialize+ * the local state syncing from the audio object+ * to our local refs.+ *+ * This lives here instead of closer to where `localAudio`+ * is defined because `initLocalAudio` and several of+ * the functions it depends on also all depend on the+ * `localAudio` variable. This is the earliest in+ * `setup` that this can be called.*/- const elPause = () => {- if (window?.audioEl) {- window.audioEl.pause()+ if (localAudio) initLocalAudio()++ onUnmounted(() => {+ if (!localAudio) return++ localAudio.removeEventListener('play', setPlaying)+ localAudio.removeEventListener('pause', setPaused)+ localAudio.removeEventListener('ended', setPlayed)+ localAudio.removeEventListener('timeupdate', setTimeWhenPaused)++ if (+ route.value.params.id == props.audio.id ||+ store.getters[`${MEDIA}/results`]?.items?.[props.audio.id]+ ) {+ /**+ * If switching to any route other than the single result+ * route for this track, pause it. Otherwise, let it keep+ * playing to introduce a "seamless" feeling beween the+ * search results page and the single result page.+ *+ * This handles going from the search page to the single+ * result page for a different track than is currently playing.+ * It also handles the same interaction for related audio.+ * Also for related audio, it will handle pausing any related+ * audio when navigating back from the single result page+ * to the search results page.+ *+ * Also, if the currently playing audio is present in the+ * existing list of search results, then also let it keep+ * playing.+ */+ return}++ localAudio.pause()+ })++ const play = () => {+ // delay initializing the local audio element until playback is requested+ if (!localAudio) initLocalAudio()+ localAudio?.play()}+ const pause = () => localAudio?.pause()+watch(- () => [store.state.active.id, store.state.active.status],- ([activeId, activeStatus], [prevActiveId, prevActiveStatus]) => {- if (activeStatus === 'ejected') {- elPause()- localPause()- } else if (activeStatus !== prevActiveStatus && isActiveTrack.value) {- // Track status changed- switch (activeStatus) {- case 'playing':- elPlay()- localPlay()- break- case 'paused':- elPause()- localPause()- break- }- } else if (activeId !== prevActiveId) {- // Track ID changed- if (isActiveTrack.value) {- elPlay()- localPlay()- } else {- localPause()- }- } else {- // Nothing changed, no action required+ activeAudio.obj,+ (audio) => {+ if (audio !== localAudio && status.value === 'playing') {+ localAudio?.pause()}- }+ },+ { immediate: true })+ /* Timekeeping */++ const duration = computed(() => (props.audio?.duration ?? 0) / 1e3) // seconds++ const message = computed(() => store.state.active.message)+/* Interface with VPlayPause *//**- * Changes the store state to 'playing' with the information about the- * track. This invokes the active media state watcher which, in turn, calls- * `elPlay` to actually play the audio.+ * @param {'playing' | 'paused'} state*/- const storePlay = () => {- store.commit(`${ACTIVE}/${SET_ACTIVE_MEDIA_ITEM}`, {- type: 'audio',- id: props.audio.id,- })- }- /**- * Changes the store state to 'paused'. If this is the active track, this- * invokes the active media state watcher which, in turn, calls `elPause` to- * actually pause the audio.- */- const storePause = () => {- store.commit(`${ACTIVE}/${PAUSE_ACTIVE_MEDIA_ITEM}`)- }const handleToggle = (state) => {switch (state) {case 'playing':- storePlay()+ play()breakcase 'paused':- if (isActiveTrack.value) {- storePause()- }+ pause()break}}@@ -268,25 +306,19 @@ export default defineComponent({/* Interface with VWaveform *//**- * Always update the current time ref when seeking happens- * for this audio track so that seeking can happen on one- * track even if it's not being played, and then that new- * time will get used if this instance's track gets played.- *- * Otherwise seeking will appear to not work on paused- * audio tracks.- ** @param {number} frac*/- const elSetTime = (frac) => {- const seekedTime = frac * (props.audio.duration / 1e3)- currentTime.value = seekedTime- if (window?.audioEl && isActiveTrack.value) {- window.audioEl.currentTime = seekedTime- }- }const handleSeeked = (frac) => {- elSetTime(frac)+ if (!localAudio) initLocalAudio()+ /**+ * Calling initLocalAudio will guarantee localAudio+ * to be an HTMLAudioElement, but we can't prove that+ * to TypeScript without jumping through some tricky+ * hoops (using `assert`) or adding unnecessary+ * runtime checks.+ */+ // @ts-ignore+ localAudio.currentTime = frac * duration.value}/* Layout */diff --git a/src/components/VAudioTrack/VGlobalAudioTrack.vue b/src/components/VAudioTrack/VGlobalAudioTrack.vuenew file mode 100644index 000000000..2e2eb986a--- /dev/null+++ b/src/components/VAudioTrack/VGlobalAudioTrack.vue@@ -0,0 +1,244 @@+<template>+ <div+ class="audio-track"+ :aria-label="$t('audio-track.aria-label')"+ role="region"+ >+ <Component :is="layoutComponent" :audio="audio" :size="size">+ <template #controller="waveformProps">+ <VWaveform+ v-bind="waveformProps"+ :peaks="audio.peaks"+ :current-time="currentTime"+ :duration="duration"+ :message="message ? $t(`audio-track.messages.${message}`) : null"+ @seeked="handleSeeked"+ />+ </template>++ <template #play-pause="playPauseProps">+ <VPlayPause+ :status="status"+ v-bind="playPauseProps"+ @toggle="handleToggle"+ />+ </template>+ </Component>+ </div>+</template>++<script>+import {+ computed,+ defineComponent,+ ref,+ useStore,+ watch,+} from '@nuxtjs/composition-api'++import { useActiveAudio } from '~/composables/use-active-audio'++import VPlayPause from '~/components/VAudioTrack/VPlayPause.vue'+import VWaveform from '~/components/VAudioTrack/VWaveform.vue'++import VFullLayout from '~/components/VAudioTrack/layouts/VFullLayout.vue'+import VRowLayout from '~/components/VAudioTrack/layouts/VRowLayout.vue'+import VBoxLayout from '~/components/VAudioTrack/layouts/VBoxLayout.vue'+import VGlobalLayout from '~/components/VAudioTrack/layouts/VGlobalLayout.vue'++const propTypes = {+ /**+ * the information about the track, typically from a track's detail endpoint+ */+ audio: {+ type: Object,+ required: true,+ },+ /**+ * the arrangement of the contents on the canvas; This determines the+ * overall L&F of the audio component.+ */+ layout: {+ type: /** @type {import('@nuxtjs/composition-api').PropType<'full' | 'box' | 'row' | 'global'>} */ (+ String+ ),+ default: 'full',+ /**+ * @param {string} val+ */+ validator: (val) => ['full', 'box', 'row', 'global'].includes(val),+ },+ /**+ * the size of the component; Both 'box' and 'row' layouts offer multiple+ * sizes to choose from.+ */+ size: {+ type: /** @type {import('@nuxtjs/composition-api').PropType<'s' | 'm' | 'l'>} */ (+ String+ ),+ default: 'm',+ /**+ * @param {string} val+ */+ validator: (val) => ['s', 'm', 'l'].includes(val),+ },+}++/**+ * Displays the waveform and basic information about the track, along with+ * controls to play, pause or seek to a point on the track.+ */+export default defineComponent({+ name: 'VGlobalAudioTrack',+ components: {+ VPlayPause,+ VWaveform,++ // Layouts+ VFullLayout,+ VRowLayout,+ VBoxLayout,+ VGlobalLayout,+ },+ props: propTypes,+ /**+ * @param {import('@nuxtjs/composition-api').ExtractPropTypes<typeof propTypes>} props+ */+ setup(props) {+ const store = useStore()++ const activeAudio = useActiveAudio()++ const status = ref('paused')+ const currentTime = ref(0)++ const setPlaying = () => {+ status.value = 'playing'+ updateTimeLoop()+ }+ const setPaused = () => (status.value = 'paused')+ const setPlayed = () => (status.value = 'played')+ /**+ * @param {Event} event+ */+ const setTimeWhenPaused = (event) => {+ if (status.value !== 'playing' && event.target) {+ currentTime.value =+ /** @type {HTMLAudioElement} */ (event.target).currentTime ?? 0+ if (status.value === 'played') {+ // Set to pause to remove replay icon+ status.value = 'paused'+ }+ }+ }++ const updateTimeLoop = () => {+ if (activeAudio.obj.value && status.value === 'playing') {+ currentTime.value = activeAudio.obj.value.currentTime+ window.requestAnimationFrame(updateTimeLoop)+ }+ }++ watch(+ activeAudio.obj,+ (audio, _, onInvalidate) => {+ if (!audio) return+ audio.addEventListener('play', setPlaying)+ audio.addEventListener('pause', setPaused)+ audio.addEventListener('ended', setPlayed)+ audio.addEventListener('timeupdate', setTimeWhenPaused)+ currentTime.value = audio.currentTime++ /**+ * By the time the `activeAudio` is updated and a rerender+ * happens (triggering this watch function), all the events+ * we've registered above will already have fired, so we+ * need to derive the current status of the audio from the+ * `paused` and `ended` booleans on the audio object.+ *+ * In practice this will always result in the status being+ * set to `playing` as the active audio is only updated when+ * a new track is set to play. But for good measure we might+ * as well do this robustly and make sure that the status is+ * always synced any time the active audio hanges.+ */+ if (audio.paused) {+ if (audio.ended) {+ setPlayed()+ } else {+ setPaused()+ }+ } else {+ setPlaying()+ }++ onInvalidate(() => {+ audio.removeEventListener('play', setPlaying)+ audio.removeEventListener('pause', setPaused)+ audio.removeEventListener('ended', setPlayed)+ audio.removeEventListener('timeupdate', setTimeWhenPaused)+ })+ },+ { immediate: true }+ )++ const play = () => activeAudio.obj.value?.play()+ const pause = () => activeAudio.obj.value?.pause()++ /* Timekeeping */++ const duration = computed(() => (props.audio?.duration ?? 0) / 1e3) // seconds++ const message = computed(() => store.state.active.message)++ /* Interface with VPlayPause */++ /**+ * @param {'playing' | 'paused'} state+ */+ const handleToggle = (state) => {+ switch (state) {+ case 'playing':+ play()+ break+ case 'paused':+ pause()+ break+ }+ }++ /* Interface with VWaveform */++ /**+ * @param {number} frac+ */+ const handleSeeked = (frac) => {+ if (activeAudio.obj.value) {+ activeAudio.obj.value.currentTime = frac * duration.value+ }+ }++ /* Layout */++ const layoutMappings = {+ full: 'VFullLayout',+ row: 'VRowLayout',+ box: 'VBoxLayout',+ global: 'VGlobalLayout',+ }+ const layoutComponent = computed(() => layoutMappings[props.layout])++ return {+ status,+ message,+ handleToggle,+ handleSeeked,++ currentTime,+ duration,++ layoutComponent,+ }+ },+})+</script>diff --git a/src/components/VGlobalAudioSection/VGlobalAudioSection.vue b/src/components/VGlobalAudioSection/VGlobalAudioSection.vueindex 759b21c28..e34231a59 100644--- a/src/components/VGlobalAudioSection/VGlobalAudioSection.vue+++ b/src/components/VGlobalAudioSection/VGlobalAudioSection.vue@@ -1,18 +1,6 @@<template><div class="global-audio sticky sm:hidden bottom-0">- <VAudioTrack v-if="audio" layout="global" :audio="audio" />-- <!-- eslint-disable vuejs-accessibility/media-has-caption -->- <audio- v-show="false"- ref="audioEl"- class="audio-controller"- controls- crossorigin="anonymous"- @error="handleError"- />- <!-- eslint-enable vuejs-accessibility/media-has-caption -->-+ <VGlobalAudioTrack v-if="audio" layout="global" :audio="audio" /><VIconButtonv-if="audio"class="absolute top-0 end-0 border-none z-10"@@ -23,15 +11,7 @@</template><script>-import {- useStore,- useRoute,- ref,- watch,- onMounted,- computed,- onBeforeUnmount,-} from '@nuxtjs/composition-api'+import { useStore, useRoute, watch, computed } from '@nuxtjs/composition-api'import { ACTIVE } from '~/constants/store-modules'import {@@ -40,6 +20,7 @@ import {} from '~/constants/mutation-types'import closeIcon from '~/assets/icons/close-small.svg'+import { useActiveAudio } from '~/composables/use-active-audio'export default {name: 'VGlobalAudioSection',@@ -47,15 +28,7 @@ export default {const store = useStore()const route = useRoute()- /* Audio element */-- const audioEl = ref(null)- onMounted(() => {- window.audioEl = audioEl.value- })- onBeforeUnmount(() => {- delete window.audioEl- })+ const activeAudio = useActiveAudio()/* Active audio track */@@ -91,6 +64,19 @@ export default {})}+ watch(+ activeAudio.obj,+ (audio, _, onInvalidate) => {+ if (!audio) return+ audio.addEventListener('error', handleError)++ onInvalidate(() => {+ audio.removeEventListener('error', handleError)+ })+ },+ { immediate: true }+ )+const handleClose = () => {store.commit(`${ACTIVE}/${EJECT_ACTIVE_MEDIA_ITEM}`)}@@ -103,7 +89,7 @@ export default {oldRouteNameVal.includes('audio') &&!routeNameVal.includes('audio')) {- audioEl.value.pause()+ activeAudio.obj.value?.pause()store.commit(`${ACTIVE}/${EJECT_ACTIVE_MEDIA_ITEM}`)}})@@ -113,8 +99,6 @@ export default {closeIcon,},- audioEl,-audio,handleError,diff --git a/src/composables/use-active-audio.js b/src/composables/use-active-audio.jsnew file mode 100644index 000000000..24f66726f--- /dev/null+++ b/src/composables/use-active-audio.js@@ -0,0 +1,8 @@+import { ref } from '@nuxtjs/composition-api'++/** @type {import('@nuxtjs/composition-api').Ref<HTMLAudioElement | undefined>} */+const obj = ref(undefined)++export function useActiveAudio() {+ return Object.freeze({ obj })+}diff --git a/tsconfig.json b/tsconfig.jsonindex c3aa6a696..53868894d 100644--- a/tsconfig.json+++ b/tsconfig.json@@ -7,8 +7,6 @@"target": "esnext","module": "esnext","lib": ["dom", "esnext"],- "declaration": true,- "declarationMap": true,"noEmit": true,"isolatedModules": true,"skipLibCheck": true,@@ -31,10 +29,11 @@"~/*": ["./src/*"],"~~/*": ["./*"]},- "baseUrl": "./"+ "baseUrl": "."},"include": ["src/composables/types.js",- "src/composables/use-event-listener-outside.js"+ "src/composables/use-event-listener-outside.js",+ "src/composables/use-active-audio.js"]}