Move track playing logic to usePlayer and useSound
This commit is contained in:
parent
54a33cd14e
commit
a43059899c
|
@ -1,20 +1,15 @@
|
|||
<script setup lang="ts">
|
||||
// TODO (wvffle): Move most of this stufff to usePlayer
|
||||
import { Track } from '~/types'
|
||||
import { useStore } from '~/store'
|
||||
import { Howl, Howler } from 'howler'
|
||||
import axios from 'axios'
|
||||
import { Howler } from 'howler'
|
||||
import VolumeControl from './VolumeControl.vue'
|
||||
import TrackFavoriteIcon from '~/components/favorites/TrackFavoriteIcon.vue'
|
||||
import TrackPlaylistIcon from '~/components/playlists/TrackPlaylistIcon.vue'
|
||||
import onKeyboardShortcut from '~/composables/onKeyboardShortcut'
|
||||
import { ref, computed, watch, onMounted, onBeforeUnmount, watchEffect } from 'vue'
|
||||
import { useTimeoutFn, useIntervalFn } from '@vueuse/core'
|
||||
import { computed, onMounted } from 'vue'
|
||||
import { useGettext } from 'vue3-gettext'
|
||||
import useQueue from '~/composables/audio/useQueue'
|
||||
import usePlayer from '~/composables/audio/usePlayer'
|
||||
import useTrackSources, { TrackSource } from '~/composables/audio/useTrackSources'
|
||||
import useSoundCache from '~/composables/audio/useSoundCache'
|
||||
|
||||
const store = useStore()
|
||||
const { $pgettext } = useGettext()
|
||||
|
@ -40,12 +35,12 @@ const {
|
|||
playing,
|
||||
loading: isLoadingAudio,
|
||||
looping,
|
||||
duration,
|
||||
currentTime,
|
||||
progress,
|
||||
durationFormatted,
|
||||
currentTimeFormatted,
|
||||
bufferProgress,
|
||||
currentTime,
|
||||
toggleMute,
|
||||
seek,
|
||||
togglePlayback,
|
||||
resume,
|
||||
|
@ -57,7 +52,7 @@ onKeyboardShortcut('e', toggleMobilePlayer)
|
|||
onKeyboardShortcut('p', togglePlayback)
|
||||
onKeyboardShortcut('s', shuffle)
|
||||
onKeyboardShortcut('q', () => store.dispatch('queue/clean'))
|
||||
onKeyboardShortcut('m', () => store.dispatch('player/toggleMute'))
|
||||
onKeyboardShortcut('m', () => toggleMute)
|
||||
onKeyboardShortcut('l', () => store.commit('player/toggleLooping'))
|
||||
onKeyboardShortcut('f', () => store.dispatch('favorites/toggle', currentTrack.value?.id))
|
||||
onKeyboardShortcut('escape', () => store.commit('ui/queueFocused', null))
|
||||
|
@ -73,43 +68,6 @@ onKeyboardShortcut(['shift', 'left'], () => seek(-30), true)
|
|||
onKeyboardShortcut(['ctrl', 'shift', 'left'], previous, true)
|
||||
onKeyboardShortcut(['ctrl', 'shift', 'right'], next, true)
|
||||
|
||||
const currentSound = ref()
|
||||
const isUpdatingTime = ref(false)
|
||||
const preloadDelay = ref(15)
|
||||
const isListeningSubmitted = ref()
|
||||
const soundId = ref()
|
||||
const nextTrackPreloaded = ref(false)
|
||||
|
||||
const maxPreloaded = ref(3)
|
||||
const soundCache = useSoundCache(maxPreloaded)
|
||||
|
||||
const updateProgress = () => {
|
||||
isUpdatingTime.value = true
|
||||
|
||||
if (currentSound.value?.state() === 'loaded') {
|
||||
const time = currentSound.value.seek()
|
||||
const duration = currentSound.value.duration()
|
||||
|
||||
store.dispatch('player/updateProgress', time)
|
||||
updateBuffer(currentSound.value._sounds[0]._node)
|
||||
|
||||
const toPreload = store.state.queue.tracks[currentIndex.value + 1]
|
||||
if (!nextTrackPreloaded.value && toPreload && !soundCache.has(toPreload.id) && (time > preloadDelay.value || duration - time < 30)) {
|
||||
getSound(toPreload)
|
||||
nextTrackPreloaded.value = true
|
||||
}
|
||||
|
||||
if (time > duration / 2) {
|
||||
if (!isListeningSubmitted.value) {
|
||||
store.dispatch('player/trackListened', currentTrack.value)
|
||||
isListeningSubmitted.value = true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// const updateProgressThrottled = useThrottleFn(updateProgress, 50)
|
||||
|
||||
const labels = computed(() => ({
|
||||
audioPlayer: $pgettext('Sidebar/Player/Hidden text', 'Media player'),
|
||||
previous: $pgettext('Sidebar/Player/Icon.Tooltip', 'Previous track'),
|
||||
|
@ -127,266 +85,15 @@ const labels = computed(() => ({
|
|||
addArtistContentFilter: $pgettext('Sidebar/Player/Icon.Tooltip/Verb', 'Hide content from this artist…')
|
||||
}))
|
||||
|
||||
// Preloading
|
||||
const { start: loadCurrentTrack, stop: cancelLoadingCurrentTrack } = useTimeoutFn(
|
||||
(track, oldValue) => loadSound(track as Track, oldValue as Track),
|
||||
100,
|
||||
{ immediate: false }
|
||||
) as { start: (a: Track, b: Track) => unknown, stop: () => void }
|
||||
|
||||
watch(currentTrack, (track, oldValue) => {
|
||||
nextTrackPreloaded.value = false
|
||||
|
||||
cancelLoadingCurrentTrack()
|
||||
|
||||
currentSound.value?.pause()
|
||||
store.commit('player/isLoadingAudio', true)
|
||||
|
||||
loadCurrentTrack(track, oldValue)
|
||||
})
|
||||
|
||||
const observeProgress = ref(false)
|
||||
useIntervalFn(() => observeProgress.value && updateProgress(), 1000)
|
||||
|
||||
watch(playing, async (isPlaying) => {
|
||||
if (currentSound.value) {
|
||||
if (isPlaying) {
|
||||
soundId.value = currentSound.value.play(soundId.value)
|
||||
} else {
|
||||
currentSound.value.pause(soundId.value)
|
||||
}
|
||||
} else {
|
||||
await loadSound(currentTrack.value)
|
||||
}
|
||||
|
||||
observeProgress.value = isPlaying
|
||||
})
|
||||
|
||||
const setCurrentTime = (time: number) => {
|
||||
if (time < 0 || time > duration.value) {
|
||||
return
|
||||
}
|
||||
|
||||
if (!currentSound.value?._sounds[0] || time === currentSound.value.seek()) {
|
||||
return
|
||||
}
|
||||
|
||||
// if (time === 0) {
|
||||
// this.updateProgressThrottled.cancel()
|
||||
// }
|
||||
|
||||
currentSound.value.seek(time)
|
||||
// If player is paused update progress immediately to ensure updated UI
|
||||
if (!playing.value) {
|
||||
updateProgress()
|
||||
}
|
||||
currentTime.value = time
|
||||
}
|
||||
|
||||
watchEffect(() => {
|
||||
if (!isUpdatingTime.value) {
|
||||
setCurrentTime(currentTime.value)
|
||||
isUpdatingTime.value = false
|
||||
}
|
||||
})
|
||||
|
||||
onMounted(() => {
|
||||
// TODO (wvffle): Check if it is needed
|
||||
store.dispatch('player/updateProgress', 0)
|
||||
// TODO (wvffle): Check if it is needed
|
||||
store.commit('player/playing', false)
|
||||
// TODO (wvffle): Check if it is needed
|
||||
store.commit('player/isLoadingAudio', false)
|
||||
|
||||
// TODO (wvffle): Check if it is needed
|
||||
Howler.unload() // clear existing cache, if any
|
||||
|
||||
// TODO (wvffle): Check if it is needed
|
||||
nextTrackPreloaded.value = false
|
||||
|
||||
// Cache sound if we have currentTrack available
|
||||
if (currentTrack.value) {
|
||||
getSound(currentTrack.value)
|
||||
}
|
||||
})
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
observeProgress.value = false
|
||||
})
|
||||
|
||||
const getSound = (trackData: Track) => {
|
||||
const cached = soundCache.get(trackData.id)
|
||||
if (cached) {
|
||||
return cached.sound
|
||||
}
|
||||
|
||||
const srcs: TrackSource[] = useTrackSources(trackData)
|
||||
const sound: Howl = new Howl({
|
||||
src: srcs.map((source) => source.url),
|
||||
format: srcs.map((source) => source.type),
|
||||
autoplay: false,
|
||||
loop: false,
|
||||
html5: true,
|
||||
preload: true,
|
||||
|
||||
onend () {
|
||||
const onlyTrack = store.state.queue.tracks.length === 1
|
||||
if (looping.value === 1 || (onlyTrack && looping.value === 2)) {
|
||||
currentSound.value.seek(0)
|
||||
store.dispatch('player/updateProgress', 0)
|
||||
soundId.value = currentSound.value.play(soundId.value)
|
||||
} else {
|
||||
store.dispatch('player/trackEnded', currentTrack.value)
|
||||
}
|
||||
},
|
||||
|
||||
onunlock () {
|
||||
if (store.state.player.playing && currentSound.value) {
|
||||
soundId.value = currentSound.value.play(soundId.value)
|
||||
}
|
||||
},
|
||||
|
||||
onload () {
|
||||
const node = (sound as any)._sounds[0]._node as HTMLAudioElement
|
||||
|
||||
node.addEventListener('progress', () => {
|
||||
if (sound !== currentSound.value) {
|
||||
return
|
||||
}
|
||||
|
||||
updateBuffer(node)
|
||||
})
|
||||
},
|
||||
|
||||
onplay () {
|
||||
if (this !== currentSound.value) {
|
||||
return (this as any).stop()
|
||||
}
|
||||
|
||||
const time = currentSound.value.seek()
|
||||
const duration = currentSound.value.duration()
|
||||
if (time <= duration / 2) {
|
||||
isListeningSubmitted.value = false
|
||||
}
|
||||
|
||||
store.commit('player/isLoadingAudio', false)
|
||||
store.commit('player/resetErrorCount')
|
||||
store.commit('player/errored', false)
|
||||
store.commit('player/duration', sound.duration())
|
||||
},
|
||||
|
||||
onplayerror (soundId, error) {
|
||||
console.log('play error', soundId, error)
|
||||
},
|
||||
|
||||
onloaderror (soundId, error) {
|
||||
console.log('load error', soundId, error)
|
||||
soundCache.delete(trackData.id)
|
||||
sound.unload()
|
||||
|
||||
if (this !== currentSound.value) {
|
||||
return
|
||||
}
|
||||
|
||||
console.error('Error while playing:', soundId, error)
|
||||
handleError()
|
||||
}
|
||||
})
|
||||
|
||||
soundCache.set(trackData.id, {
|
||||
id: trackData.id,
|
||||
date: new Date(),
|
||||
sound
|
||||
})
|
||||
|
||||
return sound
|
||||
}
|
||||
|
||||
const getTrack = async (trackData: Track) => {
|
||||
// use previously fetched trackData
|
||||
if (trackData.uploads.length) {
|
||||
return trackData
|
||||
}
|
||||
|
||||
// we don't have any information for this track, we need to fetch it
|
||||
return axios.get(`tracks/${trackData.id}/`)
|
||||
.then(response => response.data, () => null)
|
||||
}
|
||||
|
||||
const handleError = () => {
|
||||
store.commit('player/isLoadingAudio', false)
|
||||
store.dispatch('player/trackErrored')
|
||||
}
|
||||
|
||||
const updateBuffer = (node: HTMLAudioElement) => {
|
||||
// from https://github.com/goldfire/howler.js/issues/752#issuecomment-372083163
|
||||
|
||||
const { buffered, currentTime: time } = node
|
||||
|
||||
let range = 0
|
||||
try {
|
||||
while (buffered.start(range) >= time || time >= buffered.end(range)) {
|
||||
range += 1
|
||||
}
|
||||
} catch (IndexSizeError) {
|
||||
return
|
||||
}
|
||||
|
||||
let loadPercentage
|
||||
|
||||
const start = buffered.start(range)
|
||||
const end = buffered.end(range)
|
||||
|
||||
if (range === 0) {
|
||||
// easy case, no user-seek
|
||||
const loadStartPercentage = start / node.duration
|
||||
const loadEndPercentage = end / node.duration
|
||||
loadPercentage = loadEndPercentage - loadStartPercentage
|
||||
} else {
|
||||
const loaded = end - start
|
||||
const remainingToLoad = node.duration - start
|
||||
// user seeked a specific position in the audio, our progress must be
|
||||
// computed based on the remaining portion of the track
|
||||
loadPercentage = loaded / remainingToLoad
|
||||
}
|
||||
|
||||
if (loadPercentage * 100 === bufferProgress.value) {
|
||||
return
|
||||
}
|
||||
|
||||
store.commit('player/bufferProgress', loadPercentage * 100)
|
||||
}
|
||||
|
||||
const loadSound = async (trackData: Track, oldValue?: Track) => {
|
||||
const oldSound = currentSound.value
|
||||
|
||||
if (oldSound && trackData !== oldValue) {
|
||||
oldSound.stop(soundId.value)
|
||||
soundId.value = null
|
||||
}
|
||||
|
||||
if (!trackData) {
|
||||
return
|
||||
}
|
||||
|
||||
if (!isShuffling.value && trackData !== oldValue) {
|
||||
trackData = await getTrack(trackData)
|
||||
|
||||
if (trackData == null) {
|
||||
handleError()
|
||||
}
|
||||
|
||||
currentSound.value = getSound(trackData)
|
||||
|
||||
// TODO (wvffle): #1777
|
||||
soundId.value = currentSound.value.play()
|
||||
store.commit('player/isLoadingAudio', true)
|
||||
store.commit('player/errored', false)
|
||||
store.commit('player/playing', true)
|
||||
store.dispatch('player/updateProgress', 0)
|
||||
observeProgress.value = true
|
||||
}
|
||||
}
|
||||
|
||||
const switchTab = () => {
|
||||
store.commit('ui/queueFocused', store.state.ui.queueFocused === 'player' ? 'queue' : 'player')
|
||||
}
|
||||
|
|
|
@ -1,72 +1,245 @@
|
|||
import { computed, watchEffect } from "vue"
|
||||
import { Track } from '~/types'
|
||||
import { computed, watchEffect, ref, watch } from 'vue'
|
||||
import { Howler } from 'howler'
|
||||
import { useIntervalFn, useTimeoutFn } from '@vueuse/core'
|
||||
import useQueue from '~/composables/audio/useQueue'
|
||||
import useSound from '~/composables/audio/useSound'
|
||||
import toLinearVolumeScale from '~/composables/audio/toLinearVolumeScale'
|
||||
import store from "~/store"
|
||||
import store from '~/store'
|
||||
import axios from 'axios'
|
||||
|
||||
export default () => {
|
||||
const looping = computed(() => store.state.player.looping)
|
||||
const playing = computed(() => store.state.player.playing)
|
||||
const loading = computed(() => store.state.player.isLoadingAudio)
|
||||
const errored = computed(() => store.state.player.errored)
|
||||
const focused = computed(() => store.state.ui.queueFocused === 'player')
|
||||
const PRELOAD_DELAY = 15
|
||||
|
||||
// Volume
|
||||
const volume = computed({
|
||||
get: () => store.state.player.volume,
|
||||
set: (value) => store.commit('player/volume', value)
|
||||
})
|
||||
const { currentSound, loadSound, onSoundProgress } = useSound()
|
||||
const { isShuffling, currentTrack, currentIndex } = useQueue()
|
||||
|
||||
watchEffect(() => Howler.volume(toLinearVolumeScale(volume.value)))
|
||||
const looping = computed(() => store.state.player.looping)
|
||||
const playing = computed(() => store.state.player.playing)
|
||||
const loading = computed(() => store.state.player.isLoadingAudio)
|
||||
const errored = computed(() => store.state.player.errored)
|
||||
const focused = computed(() => store.state.ui.queueFocused === 'player')
|
||||
|
||||
const mute = () => store.dispatch('player/mute')
|
||||
const unmute = () => store.dispatch('player/unmute')
|
||||
const toggleMute = () => store.dispatch('player/toggleMute')
|
||||
// Cache sound if we have currentTrack available
|
||||
if (currentTrack.value) {
|
||||
loadSound(currentTrack.value)
|
||||
}
|
||||
|
||||
// Time and duration
|
||||
const duration = computed(() => store.state.player.duration)
|
||||
const currentTime = computed(() => store.state.player.currentTime)
|
||||
// Playing
|
||||
const playTrack = async (track: Track, oldTrack?: Track) => {
|
||||
const oldSound = currentSound.value
|
||||
|
||||
const durationFormatted = computed(() => store.getters['player/durationFormatted'])
|
||||
const currentTimeFormatted = computed(() => store.getters['player/currentTimeFormatted'])
|
||||
// TODO (wvffle): Move oldTrack to watcher
|
||||
if (oldSound && track !== oldTrack) {
|
||||
oldSound.stop()
|
||||
}
|
||||
|
||||
// Progress
|
||||
const progress = computed(() => store.getters['player/progress'])
|
||||
const bufferProgress = computed(() => store.state.player.bufferProgress)
|
||||
if (!track) {
|
||||
return
|
||||
}
|
||||
|
||||
// Controls
|
||||
const pause = () => store.dispatch('player/pausePlayback')
|
||||
const resume = () => store.dispatch('player/resumePlayback')
|
||||
|
||||
const { next } = useQueue()
|
||||
const seek = (step: number) => {
|
||||
// seek right
|
||||
if (step > 0) {
|
||||
if (currentTime.value + step < duration.value) {
|
||||
store.dispatch('player/updateProgress', (currentTime.value + step))
|
||||
} else {
|
||||
next()
|
||||
}
|
||||
if (!isShuffling.value) {
|
||||
if (!track.uploads.length) {
|
||||
// we don't have any information for this track, we need to fetch it
|
||||
track = await axios.get(`tracks/${track.id}/`)
|
||||
.then(response => response.data, () => null)
|
||||
}
|
||||
|
||||
if (track == null) {
|
||||
store.commit('player/isLoadingAudio', false)
|
||||
store.dispatch('player/trackErrored')
|
||||
return
|
||||
}
|
||||
|
||||
// seek left
|
||||
const position = Math.max(currentTime.value + step, 0)
|
||||
store.dispatch('player/updateProgress', position)
|
||||
currentSound.value = loadSound(track)
|
||||
|
||||
// TODO (wvffle): #1777
|
||||
currentSound.value.play()
|
||||
store.commit('player/isLoadingAudio', true)
|
||||
store.commit('player/errored', false)
|
||||
store.commit('player/playing', true)
|
||||
store.dispatch('player/updateProgress', 0)
|
||||
}
|
||||
}
|
||||
|
||||
const { start: loadTrack, stop: cancelLoading } = useTimeoutFn((track, oldTrack) => {
|
||||
playTrack(track as Track, oldTrack as Track)
|
||||
}, 100, { immediate: false }) as {
|
||||
start: (a: Track, b: Track) => void
|
||||
stop: () => void
|
||||
}
|
||||
|
||||
watch(currentTrack, (track, oldTrack) => {
|
||||
cancelLoading()
|
||||
currentSound.value?.pause()
|
||||
store.commit('player/isLoadingAudio', true)
|
||||
loadTrack(track, oldTrack)
|
||||
})
|
||||
|
||||
// Volume
|
||||
const volume = computed({
|
||||
get: () => store.state.player.volume,
|
||||
set: (value) => store.commit('player/volume', value)
|
||||
})
|
||||
|
||||
watchEffect(() => Howler.volume(toLinearVolumeScale(volume.value)))
|
||||
|
||||
const mute = () => store.dispatch('player/mute')
|
||||
const unmute = () => store.dispatch('player/unmute')
|
||||
const toggleMute = () => store.dispatch('player/toggleMute')
|
||||
|
||||
// Time and duration
|
||||
const duration = computed(() => store.state.player.duration)
|
||||
const currentTime = computed({
|
||||
get: () => store.state.player.currentTime,
|
||||
set: (time) => {
|
||||
if (time < 0 || time > duration.value) {
|
||||
return
|
||||
}
|
||||
|
||||
if (!currentSound.value.getSource() || time === currentSound.value.seek()) {
|
||||
return
|
||||
}
|
||||
|
||||
currentSound.value.seek(time)
|
||||
|
||||
// If player is paused update progress immediately to ensure updated UI
|
||||
if (!playing.value) {
|
||||
progress.value = time
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
const durationFormatted = computed(() => store.getters['player/durationFormatted'])
|
||||
const currentTimeFormatted = computed(() => store.getters['player/currentTimeFormatted'])
|
||||
|
||||
// Progress
|
||||
const progress = computed({
|
||||
get: () => store.getters['player/progress'],
|
||||
set: (time) => {
|
||||
if (currentSound.value?.state() === 'loaded') {
|
||||
const duration = currentSound.value.duration()
|
||||
|
||||
store.dispatch('player/updateProgress', time)
|
||||
currentSound.value._triggerSoundProgress()
|
||||
|
||||
const toPreload = store.state.queue.tracks[currentIndex.value + 1]
|
||||
if (!nextTrackPreloaded.value && toPreload && (time > PRELOAD_DELAY || duration - time < 30)) {
|
||||
loadSound(toPreload)
|
||||
nextTrackPreloaded.value = true
|
||||
}
|
||||
|
||||
if (time > duration / 2) {
|
||||
if (!isListeningSubmitted.value) {
|
||||
store.dispatch('player/trackListened', currentTrack.value)
|
||||
isListeningSubmitted.value = true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
const bufferProgress = computed(() => store.state.player.bufferProgress)
|
||||
onSoundProgress((node: HTMLAudioElement) => {
|
||||
// from https://github.com/goldfire/howler.js/issues/752#issuecomment-372083163
|
||||
|
||||
const { buffered, currentTime: time } = node
|
||||
|
||||
let range = 0
|
||||
try {
|
||||
while (buffered.start(range) >= time || time >= buffered.end(range)) {
|
||||
range += 1
|
||||
}
|
||||
} catch (IndexSizeError) {
|
||||
return
|
||||
}
|
||||
|
||||
const togglePlayback = () => {
|
||||
if (playing.value) return pause()
|
||||
return resume()
|
||||
let loadPercentage
|
||||
|
||||
const start = buffered.start(range)
|
||||
const end = buffered.end(range)
|
||||
|
||||
if (range === 0) {
|
||||
// easy case, no user-seek
|
||||
const loadStartPercentage = start / node.duration
|
||||
const loadEndPercentage = end / node.duration
|
||||
loadPercentage = loadEndPercentage - loadStartPercentage
|
||||
} else {
|
||||
const loaded = end - start
|
||||
const remainingToLoad = node.duration - start
|
||||
// user seeked a specific position in the audio, our progress must be
|
||||
// computed based on the remaining portion of the track
|
||||
loadPercentage = loaded / remainingToLoad
|
||||
}
|
||||
|
||||
return {
|
||||
if (loadPercentage * 100 === bufferProgress.value) {
|
||||
return
|
||||
}
|
||||
|
||||
store.commit('player/bufferProgress', loadPercentage * 100)
|
||||
})
|
||||
|
||||
const observeProgress = ref(false)
|
||||
useIntervalFn(() => {
|
||||
if (observeProgress.value && currentSound.value?.state() === 'loaded') {
|
||||
progress.value = currentSound.value.seek()
|
||||
}
|
||||
}, 1000)
|
||||
|
||||
watch(playing, async (isPlaying) => {
|
||||
if (currentSound.value) {
|
||||
if (isPlaying) {
|
||||
currentSound.value.play()
|
||||
} else {
|
||||
currentSound.value.pause()
|
||||
}
|
||||
} else {
|
||||
await playTrack(currentTrack.value)
|
||||
}
|
||||
|
||||
observeProgress.value = isPlaying
|
||||
})
|
||||
|
||||
const isListeningSubmitted = ref(false)
|
||||
const nextTrackPreloaded = ref(false)
|
||||
watch(currentTrack, () => (nextTrackPreloaded.value = false))
|
||||
|
||||
// Controls
|
||||
const pause = () => store.dispatch('player/pausePlayback')
|
||||
const resume = () => store.dispatch('player/resumePlayback')
|
||||
|
||||
const { next } = useQueue()
|
||||
const seek = (step: number) => {
|
||||
// seek right
|
||||
if (step > 0) {
|
||||
if (currentTime.value + step < duration.value) {
|
||||
store.dispatch('player/updateProgress', (currentTime.value + step))
|
||||
} else {
|
||||
next()
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// seek left
|
||||
const position = Math.max(currentTime.value + step, 0)
|
||||
store.dispatch('player/updateProgress', position)
|
||||
}
|
||||
|
||||
const togglePlayback = () => {
|
||||
if (playing.value) return pause()
|
||||
return resume()
|
||||
}
|
||||
|
||||
export default () => {
|
||||
return {
|
||||
looping,
|
||||
playing,
|
||||
loading,
|
||||
errored,
|
||||
focused,
|
||||
isListeningSubmitted,
|
||||
|
||||
playTrack,
|
||||
|
||||
volume,
|
||||
mute,
|
||||
|
@ -87,4 +260,4 @@ export default () => {
|
|||
seek,
|
||||
togglePlayback
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -8,85 +8,85 @@ import store from "~/store"
|
|||
|
||||
const { $pgettext } = gettext
|
||||
|
||||
export default () => {
|
||||
const currentTrack = computed(() => store.getters['queue/currentTrack'])
|
||||
const currentIndex = computed(() => store.state.queue.currentIndex)
|
||||
const hasNext = computed(() => store.getters['queue/hasNext'])
|
||||
const hasPrevious = computed(() => store.getters['queue/hasPrevious'])
|
||||
const currentTrack = computed(() => store.getters['queue/currentTrack'])
|
||||
const currentIndex = computed(() => store.state.queue.currentIndex)
|
||||
const hasNext = computed(() => store.getters['queue/hasNext'])
|
||||
const hasPrevious = computed(() => store.getters['queue/hasPrevious'])
|
||||
|
||||
const isEmpty = computed(() => store.getters['queue/isEmpty'])
|
||||
whenever(isEmpty, () => Howler.unload())
|
||||
const isEmpty = computed(() => store.getters['queue/isEmpty'])
|
||||
whenever(isEmpty, () => Howler.unload())
|
||||
|
||||
const removeTrack = (index: number) => store.dispatch('queue/cleanTrack', index)
|
||||
const clear = () => store.dispatch('queue/clean')
|
||||
const removeTrack = (index: number) => store.dispatch('queue/cleanTrack', index)
|
||||
const clear = () => store.dispatch('queue/clean')
|
||||
|
||||
const next = () => store.dispatch('queue/next')
|
||||
const previous = () => store.dispatch('queue/previous')
|
||||
const next = () => store.dispatch('queue/next')
|
||||
const previous = () => store.dispatch('queue/previous')
|
||||
|
||||
const focused = computed(() => store.state.ui.queueFocused === 'queue')
|
||||
const focused = computed(() => store.state.ui.queueFocused === 'queue')
|
||||
|
||||
//
|
||||
// Track list
|
||||
//
|
||||
const tracksChangeBuffer = ref<Track[] | null>(null)
|
||||
const tracks = computed<Track[]>({
|
||||
get: () => store.state.queue.tracks,
|
||||
set: (value) => (tracksChangeBuffer.value = value)
|
||||
//
|
||||
// Track list
|
||||
//
|
||||
const tracksChangeBuffer = ref<Track[] | null>(null)
|
||||
const tracks = computed<Track[]>({
|
||||
get: () => store.state.queue.tracks,
|
||||
set: (value) => (tracksChangeBuffer.value = value)
|
||||
})
|
||||
|
||||
const reorder = (oldIndex: number, newIndex: number) => {
|
||||
store.commit('queue/reorder', {
|
||||
tracks: tracksChangeBuffer.value ?? tracks.value,
|
||||
oldIndex,
|
||||
newIndex
|
||||
})
|
||||
|
||||
const reorder = (oldIndex: number, newIndex: number) => {
|
||||
store.commit('queue/reorder', {
|
||||
tracks: tracksChangeBuffer.value ?? tracks.value,
|
||||
oldIndex,
|
||||
newIndex
|
||||
tracksChangeBuffer.value = null
|
||||
}
|
||||
|
||||
//
|
||||
// Shuffle
|
||||
//
|
||||
const isShuffling = ref(false)
|
||||
|
||||
const forceShuffle = useThrottleFn(() => {
|
||||
isShuffling.value = true
|
||||
|
||||
useTimeoutFn(async () => {
|
||||
await store.dispatch('queue/shuffle')
|
||||
store.commit('ui/addMessage', {
|
||||
content: $pgettext('Content/Queue/Message', 'Queue shuffled!'),
|
||||
date: new Date()
|
||||
})
|
||||
|
||||
tracksChangeBuffer.value = null
|
||||
isShuffling.value = false
|
||||
}, 100)
|
||||
})
|
||||
|
||||
const shuffle = useThrottleFn(() => {
|
||||
if (isShuffling.value || isEmpty.value) {
|
||||
return
|
||||
}
|
||||
|
||||
//
|
||||
// Shuffle
|
||||
//
|
||||
const isShuffling = ref(false)
|
||||
return forceShuffle()
|
||||
}, 101, false)
|
||||
|
||||
const forceShuffle = useThrottleFn(() => {
|
||||
isShuffling.value = true
|
||||
//
|
||||
// Time left
|
||||
//
|
||||
const now = useNow()
|
||||
const endsIn = useTimeAgo(computed(() => {
|
||||
const seconds = sum(
|
||||
tracks.value
|
||||
.slice(currentIndex.value)
|
||||
.map((track) => track.uploads?.[0]?.duration ?? 0)
|
||||
)
|
||||
|
||||
useTimeoutFn(async () => {
|
||||
await store.dispatch('queue/shuffle')
|
||||
store.commit('ui/addMessage', {
|
||||
content: $pgettext('Content/Queue/Message', 'Queue shuffled!'),
|
||||
date: new Date()
|
||||
})
|
||||
|
||||
isShuffling.value = false
|
||||
}, 100)
|
||||
})
|
||||
|
||||
const shuffle = useThrottleFn(() => {
|
||||
if (isShuffling.value || isEmpty.value) {
|
||||
return
|
||||
}
|
||||
|
||||
return forceShuffle()
|
||||
}, 101, false)
|
||||
|
||||
//
|
||||
// Time left
|
||||
//
|
||||
const now = useNow()
|
||||
const endsIn = useTimeAgo(computed(() => {
|
||||
const seconds = sum(
|
||||
tracks.value
|
||||
.slice(currentIndex.value)
|
||||
.map((track) => track.uploads?.[0]?.duration ?? 0)
|
||||
)
|
||||
|
||||
const date = new Date(now.value)
|
||||
date.setSeconds(date.getSeconds() + seconds)
|
||||
return date
|
||||
}))
|
||||
const date = new Date(now.value)
|
||||
date.setSeconds(date.getSeconds() + seconds)
|
||||
return date
|
||||
}))
|
||||
|
||||
export default () => {
|
||||
return {
|
||||
currentTrack,
|
||||
currentIndex,
|
||||
|
|
|
@ -0,0 +1,148 @@
|
|||
import { ref, computed } from "vue"
|
||||
import { Track } from '~/types'
|
||||
import { Howl } from 'howler'
|
||||
import useTrackSources from '~/composables/audio/useTrackSources'
|
||||
import useSoundCache from '~/composables/audio/useSoundCache'
|
||||
import usePlayer from '~/composables/audio/usePlayer'
|
||||
import store from "~/store"
|
||||
import { createEventHook } from "@vueuse/core"
|
||||
|
||||
interface Sound {
|
||||
id?: number
|
||||
howl: Howl
|
||||
stop: () => void
|
||||
play: () => void
|
||||
pause: () => void
|
||||
state: () => 'unloaded' | 'loading' | 'loaded'
|
||||
seek: (time?: number) => number
|
||||
duration: () => number
|
||||
getSource: () => boolean
|
||||
_triggerSoundProgress: () => void
|
||||
}
|
||||
|
||||
const soundCache = useSoundCache()
|
||||
const currentTrack = computed(() => store.getters['queue/currentTrack'])
|
||||
const looping = computed(() => store.state.player.looping)
|
||||
|
||||
const currentSound = ref()
|
||||
const soundId = ref()
|
||||
|
||||
const soundProgress = createEventHook<HTMLAudioElement>()
|
||||
|
||||
const createSound = (howl: Howl): Sound => ({
|
||||
howl,
|
||||
play () {
|
||||
this.id = howl.play(this.id)
|
||||
},
|
||||
stop () {
|
||||
howl.stop(this.id)
|
||||
this.id = undefined
|
||||
},
|
||||
pause () {
|
||||
howl.pause(this.id)
|
||||
},
|
||||
state: () => howl.state(),
|
||||
seek: (time?: number) => howl.seek(time),
|
||||
duration: () => howl.duration(),
|
||||
getSource: () => (howl as any)._sounds[0],
|
||||
_triggerSoundProgress: () => soundProgress.trigger((howl as any)._sounds[0]._node)
|
||||
})
|
||||
|
||||
const loadSound = (track: Track): Sound => {
|
||||
const cached = soundCache.get(track.id)
|
||||
if (cached) {
|
||||
return createSound(cached.howl)
|
||||
}
|
||||
|
||||
const sources = useTrackSources(track)
|
||||
|
||||
const howl = new Howl({
|
||||
src: sources.map((source) => source.url),
|
||||
format: sources.map((source) => source.type),
|
||||
autoplay: false,
|
||||
loop: false,
|
||||
html5: true,
|
||||
preload: true,
|
||||
|
||||
onend () {
|
||||
const onlyTrack = store.state.queue.tracks.length === 1
|
||||
if (looping.value === 1 || (onlyTrack && looping.value === 2)) {
|
||||
currentSound.value.seek(0)
|
||||
store.dispatch('player/updateProgress', 0)
|
||||
soundId.value = currentSound.value.play(soundId.value)
|
||||
} else {
|
||||
store.dispatch('player/trackEnded', currentTrack.value)
|
||||
}
|
||||
},
|
||||
|
||||
onunlock () {
|
||||
if (store.state.player.playing && currentSound.value) {
|
||||
soundId.value = currentSound.value.play(soundId.value)
|
||||
}
|
||||
},
|
||||
|
||||
onload () {
|
||||
const node = (howl as any)._sounds[0]._node as HTMLAudioElement
|
||||
|
||||
node.addEventListener('progress', () => {
|
||||
if (howl !== currentSound.value) {
|
||||
return
|
||||
}
|
||||
|
||||
currentSound.value._triggerSoundProgress()
|
||||
})
|
||||
},
|
||||
|
||||
onplay () {
|
||||
if (this !== currentSound.value?.howl) {
|
||||
return (this as any).stop()
|
||||
}
|
||||
|
||||
const time = currentSound.value.seek()
|
||||
const duration = currentSound.value.duration()
|
||||
if (time <= duration / 2) {
|
||||
const { isListeningSubmitted } = usePlayer()
|
||||
isListeningSubmitted.value = false
|
||||
}
|
||||
|
||||
store.commit('player/isLoadingAudio', false)
|
||||
store.commit('player/resetErrorCount')
|
||||
store.commit('player/errored', false)
|
||||
store.commit('player/duration', howl.duration())
|
||||
},
|
||||
|
||||
onplayerror (soundId, error) {
|
||||
console.error('play error', soundId, error)
|
||||
},
|
||||
|
||||
onloaderror (soundId, error) {
|
||||
soundCache.delete(track.id)
|
||||
howl.unload()
|
||||
|
||||
if (this !== currentSound.value?.howl) {
|
||||
console.error('load error', soundId, error)
|
||||
return
|
||||
}
|
||||
|
||||
console.error('Error while playing:', soundId, error)
|
||||
store.commit('player/isLoadingAudio', false)
|
||||
store.dispatch('player/trackErrored')
|
||||
}
|
||||
})
|
||||
|
||||
soundCache.set(track.id, {
|
||||
id: track.id,
|
||||
date: new Date(),
|
||||
howl
|
||||
})
|
||||
|
||||
return createSound(howl)
|
||||
}
|
||||
|
||||
export default () => {
|
||||
return {
|
||||
loadSound,
|
||||
currentSound,
|
||||
onSoundProgress: soundProgress.on
|
||||
}
|
||||
}
|
|
@ -1,36 +1,38 @@
|
|||
import { MaybeRef } from "@vueuse/core"
|
||||
import { Howl } from "howler"
|
||||
import { sortBy } from "lodash-es"
|
||||
import { reactive, watchEffect, ref, unref } from "vue"
|
||||
import { reactive, watchEffect, ref } from "vue"
|
||||
|
||||
const MAX_PRELOADED = 3
|
||||
|
||||
export interface CachedSound {
|
||||
id: string
|
||||
date: Date
|
||||
sound: Howl
|
||||
howl: Howl
|
||||
}
|
||||
|
||||
export default (maxPreloaded: MaybeRef<number>) => {
|
||||
const soundCache = reactive(new Map<string, CachedSound>())
|
||||
const cleaningCache = ref(false)
|
||||
const soundCache = reactive(new Map<string, CachedSound>())
|
||||
const cleaningCache = ref(false)
|
||||
|
||||
watchEffect(() => {
|
||||
let toRemove = soundCache.size - unref(maxPreloaded)
|
||||
watchEffect(() => {
|
||||
let toRemove = soundCache.size - MAX_PRELOADED
|
||||
|
||||
if (toRemove > 0 && !cleaningCache.value) {
|
||||
cleaningCache.value = true
|
||||
if (toRemove > 0 && !cleaningCache.value) {
|
||||
cleaningCache.value = true
|
||||
|
||||
const excess = sortBy([...soundCache.values()], [(cached: CachedSound) => cached.date])
|
||||
.slice(0, toRemove)
|
||||
const excess = sortBy([...soundCache.values()], [(cached: CachedSound) => cached.date])
|
||||
.slice(0, toRemove)
|
||||
|
||||
for (const cached of excess) {
|
||||
console.log('Removing cached element:', cached)
|
||||
soundCache.delete(cached.id)
|
||||
cached.sound.unload()
|
||||
}
|
||||
|
||||
cleaningCache.value = false
|
||||
for (const cached of excess) {
|
||||
console.log('Removing cached element:', cached)
|
||||
soundCache.delete(cached.id)
|
||||
cached.howl.unload()
|
||||
}
|
||||
})
|
||||
|
||||
cleaningCache.value = false
|
||||
}
|
||||
})
|
||||
|
||||
|
||||
export default () => {
|
||||
return soundCache
|
||||
}
|
|
@ -1,17 +0,0 @@
|
|||
import { InitModule } from '~/types'
|
||||
import { Howl } from 'howler'
|
||||
|
||||
export const install: InitModule = ({ app }) => {
|
||||
// TODO (wvffle): Check if it is needed
|
||||
|
||||
// this is needed to unlock audio playing under some browsers,
|
||||
// cf https://github.com/goldfire/howler.js#mobilechrome-playback
|
||||
// but we never actually load those audio files
|
||||
// const dummyAudio = new Howl({
|
||||
// preload: false,
|
||||
// autoplay: false,
|
||||
// src: ['noop.webm', 'noop.mp3']
|
||||
// })
|
||||
|
||||
// return dummyAudio
|
||||
}
|
Loading…
Reference in New Issue