Make embedded Player functional

This commit is contained in:
Georg Krause 2021-10-26 11:16:10 +02:00
parent 1b49c0e259
commit 959a78c353
No known key found for this signature in database
GPG Key ID: FD479B9A4D48E632
3 changed files with 787 additions and 59 deletions

View File

@ -29,59 +29,7 @@
<h3><a :href="fullUrl('/library/tracks/' + currentTrack.id)" target="_blank" rel="noopener noreferrer">{{ currentTrack.title }}</a></h3>
<a :href="fullUrl('/library/artists/' + currentTrack.artist.id)" target="_blank" rel="noopener noreferrer">{{ currentTrack.artist.name }}</a>
</header>
<section v-if="!isLoading" class="controls" aria-label="Audio player">
<template v-if="currentTrack && currentTrack.sources.length > 0">
<div class="queue-controls plyr--audio" v-if="tracks.length > 1">
<div class="plyr__controls">
<button
@focus="setControlFocus($event, true)"
@blur="setControlFocus($event, false)"
@click="previous()"
type="button"
class="plyr__control"
aria-label="Play previous track">
<svg class="icon--not-pressed" role="presentation" focusable="false" viewBox="0 0 1100 1650" width="80" height="80">
<use xlink:href="#plyr-step-backward"></use>
</svg>
</button>
<button
@click="next()"
@focus="setControlFocus($event, true)"
@blur="setControlFocus($event, false)"
type="button"
class="plyr__control"
aria-label="Play next track">
<svg class="icon--not-pressed" role="presentation" focusable="false" viewBox="0 0 1100 1650" width="80" height="80">
<use xlink:href="#plyr-step-forward"></use>
</svg>
</button>
</div>
</div>
<vue-plyr
:key="currentIndex"
ref="player"
class="player"
:options="{loadSprite: false, controls: controls, duration: currentTrack.sources[0].duration, autoplay}">
<audio preload="none">
<source v-for="source in currentTrack.sources" :src="source.src" :type="source.type"/>
</audio>
</vue-plyr>
</template>
<div v-else class="player">
<span v-if="error === 'invalid_type'" class="error">Widget improperly configured (bad resource type {{ type }}).</span>
<span v-else-if="error === 'invalid_id'" class="error">Widget improperly configured (missing resource id).</span>
<span v-else-if="error === 'server_not_found'" class="error">Track not found.</span>
<span v-else-if="error === 'server_requires_auth'" class="error">You need to login to access this resource.</span>
<span v-else-if="error === 'server_error'" class="error">A server error occurred.</span>
<span v-else-if="error === 'server_error'" class="error">An unknown error occurred while loading track data from server.</span>
<span v-else-if="currentTrack && currentTrack.sources.length === 0" class="error">This track is unavailable.</span>
<span v-else class="error">An unknown error occurred while loading track data.</span>
</div>
<a title="Funkwhale" href="https://funkwhale.audio" target="_blank" rel="noopener noreferrer" class="logo-wrapper">
<logo :fill="currentTheme.textColor" class="logo"></logo>
</a>
</section>
<Player></Player>
</div>
</article>
<div v-if="tracks.length > 1" class="queue-wrapper" id="queue">
@ -119,6 +67,7 @@ import axios from 'axios'
import Logo from "@/components/Logo"
import url from '@/utils/url'
import time from '@/utils/time'
import Player from '@/components/audio/PlayerCopy'
function getURLParams () {
var urlParams
@ -135,7 +84,7 @@ function getURLParams () {
}
export default {
name: 'app',
components: {Logo},
components: {Logo, Player},
data () {
return {
time,
@ -175,6 +124,7 @@ export default {
if (!!params.instance) {
this.baseUrl = params.instance
}
this.$store.dispatch('instance/setUrl', this.baseUrl)
this.autoplay = params.autoplay != undefined || params.auto_play != undefined
this.fetch(this.type, this.id)
@ -256,7 +206,9 @@ export default {
let self = this
let url = `${this.baseUrl}/api/v1/tracks/${id}/`
axios.get(url).then(response => {
self.tracks = self.parseTracks([response.data])
self.tracks = response.data
self.$store.dispatch('queue/append', {track: self.tracks})
self.$store.dispatch('queue/next')
self.isLoading = false;
}).catch(error => {
if (error.response) {
@ -326,9 +278,9 @@ export default {
},
bindEvents () {
let self = this
this.$refs.player.player.on('ended', () => {
self.next()
})
//this.$refs.player.player.on('ended', () => {
// self.next()
//})
},
fullUrl (path) {
if (path.startsWith('/')) {

View File

@ -0,0 +1,731 @@
<template>
<section role="complementary" v-if="currentTrack" class="player-wrapper ui bottom-player component-player" aria-labelledby="player-label">
<h1 id="player-label" class="visually-hidden">
<translate translate-context="*/*/*">Audio player and controls</translate>
</h1>
<div class="ui inverted segment fixed-controls" @click.prevent.stop="toggleMobilePlayer">
<div
:class="['ui', 'top attached', 'small', 'inverted', {'indicating': isLoadingAudio}, 'progress']">
<div class="buffer bar" :data-percent="bufferProgress" :style="{ 'width': bufferProgress + '%' }"></div>
<div class="position bar" :data-percent="progress" :style="{ 'width': progress + '%' }"></div>
</div>
<div class="controls-row">
<div class="controls track-controls queue-not-focused desktop-and-up">
<div class="ui tiny image" @click.stop.prevent="$router.push({name: 'library.tracks.detail', params: {id: currentTrack.id }})">
<img alt="" ref="cover" v-if="currentTrack.cover && currentTrack.cover.urls && currentTrack.cover.urls.original" :src="$store.getters['instance/absoluteUrl'](currentTrack.cover.urls.medium_square_crop)">
<img alt="" ref="cover" v-else-if="currentTrack.album && currentTrack.album.cover && currentTrack.album.cover.urls && currentTrack.album.cover.urls.original" :src="$store.getters['instance/absoluteUrl'](currentTrack.album.cover.urls.medium_square_crop)">
<img alt="" v-else src="../../assets/audio/default-cover.png">
</div>
<div @click.stop.prevent="" class="middle aligned content ellipsis">
<strong>
{{ currentTrack.title }}
</strong>
<div class="meta">
{{ currentTrack.artist.name }}
<template v-if="currentTrack.album"> /
{{ currentTrack.album.title }}
</template>
</div>
</div>
</div>
<div class="controls track-controls queue-not-focused tablet-and-below">
<div class="ui tiny image">
<img alt="" ref="cover" v-if="currentTrack.cover && currentTrack.cover.urls && currentTrack.cover.urls.original" :src="$store.getters['instance/absoluteUrl'](currentTrack.cover.urls.medium_square_crop)">
<img alt="" ref="cover" v-else-if="currentTrack.album && currentTrack.album.cover && currentTrack.album.cover.urls.original" :src="$store.getters['instance/absoluteUrl'](currentTrack.album.cover.urls.medium_square_crop)">
<img alt="" v-else src="../../assets/audio/default-cover.png">
</div>
<div class="middle aligned content ellipsis">
<strong>
{{ currentTrack.title }}
</strong>
<div class="meta">
{{ currentTrack.artist.name }}<template v-if="currentTrack.album"> / {{ currentTrack.album.title }}</template>
</div>
</div>
</div>
<div class="player-controls controls queue-not-focused">
<button
:title="labels.previous"
:aria-label="labels.previous"
class="circular button control tablet-and-up"
@click.prevent.stop="$store.dispatch('queue/previous')"
:disabled="!hasPrevious">
<i :class="['ui', 'large', {'disabled': !hasPrevious}, 'backward step', 'icon']" ></i>
</button>
<button
v-if="!playing"
:title="labels.play"
:aria-label="labels.play"
@click.prevent.stop="resumePlayback"
class="circular button control">
<i :class="['ui', 'big', 'play', {'disabled': !currentTrack}, 'icon']"></i>
</button>
<button
v-else
:title="labels.pause"
:aria-label="labels.pause"
@click.prevent.stop="pausePlayback"
class="circular button control">
<i :class="['ui', 'big', 'pause', {'disabled': !currentTrack}, 'icon']"></i>
</button>
<button
:title="labels.next"
:aria-label="labels.next"
class="circular button control"
@click.prevent.stop="$store.dispatch('queue/next')"
:disabled="!hasNext">
<i :class="['ui', 'large', {'disabled': !hasNext}, 'forward step', 'icon']" ></i>
</button>
</div>
<div class="controls progress-controls queue-not-focused tablet-and-up small align-left">
<div class="timer">
<template v-if="!isLoadingAudio">
<span class="start" @click.stop.prevent="setCurrentTime(0)">{{currentTimeFormatted}}</span>
| <span class="total">{{durationFormatted}}</span>
</template>
<template v-else>
00:00 | 00:00
</template>
</div>
</div>
<div class="controls queue-controls when-queue-focused align-right">
<div class="group">
<volume-control class="expandable" />
<button
class="circular control button"
v-if="looping === 0"
:title="labels.loopingDisabled"
:aria-label="labels.loopingDisabled"
@click.prevent.stop="$store.commit('player/looping', 1)"
:disabled="!currentTrack">
<i :class="['ui', {'disabled': !currentTrack}, 'step', 'repeat', 'icon']"></i>
</button>
<button
class="looping circular control button"
@click.prevent.stop="$store.commit('player/looping', 2)"
:title="labels.loopingSingle"
:aria-label="labels.loopingSingle"
v-if="looping === 1"
:disabled="!currentTrack">
<i
class="repeat icon">
<span class="ui circular tiny vibrant label">1</span>
</i>
</button>
<button
class="looping circular control button"
:title="labels.loopingWhole"
:aria-label="labels.loopingWhole"
v-if="looping === 2"
:disabled="!currentTrack"
@click.prevent.stop="$store.commit('player/looping', 0)">
<i
class="repeat icon">
<span class="ui circular tiny vibrant label">&infin;</span>
</i>
</button>
<button
class="circular control button"
:disabled="queue.tracks.length === 0"
:title="labels.shuffle"
:aria-label="labels.shuffle"
@click.prevent.stop="shuffle()">
<div v-if="isShuffling" class="ui inline shuffling inverted tiny active loader"></div>
<i v-else :class="['ui', 'random', {'disabled': queue.tracks.length === 0}, 'icon']" ></i>
</button>
</div>
<div class="group">
<div class="fake-dropdown">
<button class="position circular control button desktop-and-up" @click.stop="toggleMobilePlayer" aria-expanded="true">
<i class="stream icon"></i>
<translate translate-context="Sidebar/Queue/Text" :translate-params="{index: queue.currentIndex + 1, length: queue.tracks.length}">
%{ index } of %{ length }
</translate>
</button>
<button class="position circular control button tablet-and-below" @click.stop="switchTab">
<i class="stream icon"></i>
<translate translate-context="Sidebar/Queue/Text" :translate-params="{index: queue.currentIndex + 1, length: queue.tracks.length}">
%{ index } of %{ length }
</translate>
</button>
</div>
<button
class="circular control button close-control tablet-and-below"
@click.stop="$store.commit('ui/queueFocused', null)">
<i class="x icon"></i>
</button>
</div>
</div>
</div>
</div>
<GlobalEvents
@keydown.p.prevent.exact="togglePlayback"
@keydown.esc.prevent.exact="$store.commit('ui/queueFocused', null)"
@keydown.ctrl.shift.left.prevent.exact="previous"
@keydown.ctrl.shift.right.prevent.exact="next"
@keydown.shift.down.prevent.exact="$store.commit('player/incrementVolume', -0.1)"
@keydown.shift.up.prevent.exact="$store.commit('player/incrementVolume', 0.1)"
@keydown.right.prevent.exact="seek (5)"
@keydown.left.prevent.exact="seek (-5)"
@keydown.shift.right.prevent.exact="seek (30)"
@keydown.shift.left.prevent.exact="seek (-30)"
@keydown.m.prevent.exact="toggleMute"
@keydown.l.exact="$store.commit('player/toggleLooping')"
@keydown.s.exact="shuffle"
@keydown.f.exact="$store.dispatch('favorites/toggle', currentTrack.id)"
@keydown.q.exact="clean"
@keydown.e.exact="toggleMobilePlayer"
/>
</section>
</template>
<script>
import { mapState, mapGetters, mapActions } from 'vuex'
import GlobalEvents from '@/components/utils/global-events'
import { toLinearVolumeScale } from '@/audio/volume'
import { Howl, Howler } from 'howler'
import _ from '@/lodash'
import url from '@/utils/url'
import axios from 'axios'
export default {
components: {
VolumeControl: () => import(/* webpackChunkName: "audio" */ './VolumeControl'),
TrackFavoriteIcon: () => import(/* webpackChunkName: "auth-audio" */ '@/components/favorites/TrackFavoriteIcon'),
TrackPlaylistIcon: () => import(/* webpackChunkName: "auth-audio" */ '@/components/playlists/TrackPlaylistIcon'),
GlobalEvents
},
data () {
return {
isShuffling: false,
sliderVolume: this.volume,
showVolume: false,
currentSound: null,
dummyAudio: null,
isUpdatingTime: false,
sourceErrors: 0,
progressInterval: null,
maxPreloaded: 3,
preloadDelay: 15,
listenDelay: 15,
listeningRecorded: null,
soundsCache: [],
soundId: null,
playTimeout: null,
nextTrackPreloaded: false
}
},
mounted () {
this.$store.dispatch('player/updateProgress', 0)
this.$store.commit('player/playing', false)
this.$store.commit('player/isLoadingAudio', false)
Howler.unload() // clear existing cache, if any
this.nextTrackPreloaded = false
// 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
this.dummyAudio = new Howl({
preload: false,
autoplay: false,
src: ['noop.webm', 'noop.mp3']
})
if (this.currentTrack) {
this.getSound(this.currentTrack)
this.updateMetadata()
}
// Add controls for notification drawer
if ('mediaSession' in navigator) {
navigator.mediaSession.setActionHandler('play', this.resumePlayback)
navigator.mediaSession.setActionHandler('pause', this.pausePlayback)
navigator.mediaSession.setActionHandler('seekforward', this.seekForward)
navigator.mediaSession.setActionHandler('seekbackward', this.seekBackward)
navigator.mediaSession.setActionHandler('nexttrack', this.next)
navigator.mediaSession.setActionHandler('previoustrack', this.previous)
}
},
beforeDestroy () {
this.dummyAudio.unload()
this.observeProgress(false)
},
destroyed () {
},
methods: {
...mapActions({
resumePlayback: 'player/resumePlayback',
pausePlayback: 'player/pausePlayback',
togglePlayback: 'player/togglePlayback',
mute: 'player/mute',
unmute: 'player/unmute',
clean: 'queue/clean',
toggleMute: 'player/toggleMute'
}),
async getTrackData (trackData) {
// use previously fetched trackData
if (trackData && trackData.uploads && trackData.uploads.length) return trackData
// we don't have any information for this track, we need to fetch it
return axios.get(`https://open.audio/api/v1/tracks/${trackData.id}/`)
.then(
response => response.data,
() => null
)
},
shuffle () {
const disabled = this.queue.tracks.length === 0
if (this.isShuffling || disabled) {
return
}
const self = this
const msg = this.$pgettext('Content/Queue/Message', 'Queue shuffled!')
this.isShuffling = true
setTimeout(() => {
self.$store.dispatch('queue/shuffle', () => {
self.isShuffling = false
self.$store.commit('ui/addMessage', {
content: msg,
date: new Date()
})
})
}, 100)
},
next () {
const self = this
this.$store.dispatch('queue/next').then(() => {
self.$emit('next')
})
},
previous () {
const self = this
this.$store.dispatch('queue/previous').then(() => {
self.$emit('previous')
})
},
handleError ({ sound, error }) {
this.$store.commit('player/isLoadingAudio', false)
this.$store.dispatch('player/trackErrored')
},
getSound (trackData) {
const cached = this.getSoundFromCache(trackData)
if (cached) {
return cached.sound
}
const srcs = this.getSrcs(trackData)
const self = this
const sound = new Howl({
src: srcs.map((s) => { return s.url }),
format: srcs.map((s) => { return s.type }),
autoplay: false,
loop: false,
html5: true,
preload: true,
onend: function () {
self.ended()
},
onunlock: function () {
if (self.$store.state.player.playing && self.sound) {
self.soundId = self.sound.play(self.soundId)
}
},
onload: function () {
const sound = this
const node = this._sounds[0]._node
node.addEventListener('progress', () => {
if (sound !== self.currentSound) {
return
}
self.updateBuffer(node)
})
},
onplay: function () {
if (this !== self.currentSound) {
this.stop()
return
}
self.$store.commit('player/isLoadingAudio', false)
self.$store.commit('player/resetErrorCount')
self.$store.commit('player/errored', false)
self.$store.commit('player/duration', this.duration())
},
onloaderror: function (sound, error) {
self.removeFromCache(this)
if (this !== self.currentSound) {
return
}
console.log('Error while playing:', sound, error)
self.handleError({ sound, error })
}
})
this.addSoundToCache(sound, trackData)
return sound
},
getSrcs: function (trackData) {
const a = document.createElement('audio')
const allowed = ['probably', 'maybe']
const sources = trackData.uploads.filter(u => {
const canPlay = a.canPlayType(u.mimetype)
return allowed.indexOf(canPlay) > -1
}).map(u => {
return {
type: u.extension,
url: this.$store.getters['instance/absoluteUrl'](u.listen_url)
}
})
a.remove()
// We always add a transcoded MP3 src at the end
// because transcoding is expensive, but we want browsers that do
// not support other codecs to be able to play it :)
//sources.push({
// type: 'mp3',
// url: url.updateQueryString(
// this.$store.getters['instance/absoluteUrl'](trackData.listen_url),
// 'to',
// 'mp3'
// )
//})
return sources
},
updateBuffer (node) {
// from https://github.com/goldfire/howler.js/issues/752#issuecomment-372083163
let range = 0
const bf = node.buffered
const time = node.currentTime
try {
while (!(bf.start(range) <= time && time <= bf.end(range))) {
range += 1
}
} catch (IndexSizeError) {
return
}
let loadPercentage
const start = bf.start(range)
const end = bf.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 === this.bufferProgress) {
return
}
this.$store.commit('player/bufferProgress', loadPercentage * 100)
},
updateProgress: function () {
this.isUpdatingTime = true
if (this.currentSound && this.currentSound.state() === 'loaded') {
const t = this.currentSound.seek()
const d = this.currentSound.duration()
this.$store.dispatch('player/updateProgress', t)
this.updateBuffer(this.currentSound._sounds[0]._node)
const toPreload = this.$store.state.queue.tracks[this.currentIndex + 1]
if (!this.nextTrackPreloaded && toPreload && !this.getSoundFromCache(toPreload) && (t > this.preloadDelay || d - t < 30)) {
this.getSound(toPreload)
this.nextTrackPreloaded = true
}
if (t > (d / 2)) {
if (this.listeningRecorded !== this.currentTrack) {
this.listeningRecorded = this.currentTrack
this.$store.dispatch('player/trackListened', this.currentTrack)
}
}
}
},
seek (step) {
if (step > 0) {
// seek right
if (this.currentTime + step < this.duration) {
this.$store.dispatch('player/updateProgress', (this.currentTime + step))
} else {
this.next() // parenthesis where missing here
}
} else {
// seek left
const position = Math.max(this.currentTime + step, 0)
this.$store.dispatch('player/updateProgress', position)
}
},
seekForward () {
this.seek(5)
},
seekBackward () {
this.seek(-5)
},
observeProgress: function (enable) {
const self = this
if (enable) {
if (self.progressInterval) {
clearInterval(self.progressInterval)
}
self.progressInterval = setInterval(() => {
self.updateProgress()
}, 1000)
} else {
clearInterval(self.progressInterval)
}
},
setCurrentTime (t) {
if (t < 0 | t > this.duration) {
return
}
if (!this.currentSound || !this.currentSound._sounds[0]) {
return
}
if (t === this.currentSound.seek()) {
return
}
if (t === 0) {
this.updateProgressThrottled.cancel()
}
this.currentSound.seek(t)
// If player is paused update progress immediately to ensure updated UI
if (!this.$store.state.player.playing) {
this.updateProgress()
}
},
ended: function () {
const onlyTrack = this.$store.state.queue.tracks.length === 1
if (this.looping === 1 || (onlyTrack && this.looping === 2)) {
this.currentSound.seek(0)
this.$store.dispatch('player/updateProgress', 0)
this.soundId = this.currentSound.play(this.soundId)
} else {
this.$store.dispatch('player/trackEnded', this.currentTrack)
}
},
getSoundFromCache (trackData) {
return this.soundsCache.filter((d) => {
if (d.track.id !== trackData.id) {
return false
}
return true
})[0]
},
addSoundToCache (sound, trackData) {
const data = {
date: new Date(),
track: trackData,
sound: sound
}
this.soundsCache.push(data)
this.checkCache()
},
checkCache () {
const self = this
const toKeep = []
_.reverse(this.soundsCache).forEach((e) => {
if (toKeep.length < self.maxPreloaded) {
toKeep.push(e)
} else {
e.sound.unload()
}
})
this.soundsCache = _.reverse(toKeep)
},
removeFromCache (sound) {
const toKeep = []
this.soundsCache.forEach((e) => {
if (e.sound === sound) {
e.sound.unload()
} else {
toKeep.push(e)
}
})
this.soundsCache = toKeep
},
async loadSound (newValue, oldValue) {
let trackData = newValue
const oldSound = this.currentSound
// stop all other sounds!
// we do this here (before the track has loaded) to get a predictable
// song order.
Howler.stop()
if (oldSound && trackData !== oldValue) {
this.soundId = null
}
if (!trackData) {
return
}
if (!this.isShuffling && trackData !== oldValue) {
trackData = await this.getTrackData(trackData)
if (trackData == null) {
this.handleError({})
}
this.currentSound = this.getSound(trackData)
this.$store.commit('player/isLoadingAudio', true)
this.soundId = this.currentSound.play()
this.$store.commit('player/errored', false)
this.$store.commit('player/playing', true)
this.$store.dispatch('player/updateProgress', 0)
this.observeProgress(true)
}
},
toggleMobilePlayer () {
//if (['queue', 'player'].indexOf(this.$store.state.ui.queueFocused) > -1) {
// this.$store.commit('ui/queueFocused', null)
//} else {
// this.$store.commit('ui/queueFocused', 'player')
//}
},
switchTab () {
//if (this.$store.state.ui.queueFocused === 'player') {
// this.$store.commit('ui/queueFocused', 'queue')
//} else {
// this.$store.commit('ui/queueFocused', 'player')
//}
},
updateMetadata () {
// If the session is playing as a PWA, populate the notification
// with details from the track
if (this.currentTrack && 'mediaSession' in navigator) {
const metadata = {
title: this.currentTrack.title,
artist: this.currentTrack.artist.name
}
if (this.currentTrack.album && this.currentTrack.album.cover) {
metadata.album = this.currentTrack.album.title
metadata.artwork = [
{ src: this.currentTrack.album.cover.urls.original, sizes: '96x96', type: 'image/png' },
{ src: this.currentTrack.album.cover.urls.original, sizes: '128x128', type: 'image/png' },
{ src: this.currentTrack.album.cover.urls.original, sizes: '192x192', type: 'image/png' },
{ src: this.currentTrack.album.cover.urls.original, sizes: '256x256', type: 'image/png' },
{ src: this.currentTrack.album.cover.urls.original, sizes: '384x384', type: 'image/png' },
{ src: this.currentTrack.album.cover.urls.original, sizes: '512x512', type: 'image/png' }
]
}
navigator.mediaSession.metadata = new window.MediaMetadata(metadata)
}
}
},
computed: {
...mapState({
currentIndex: state => state.queue.currentIndex,
playing: state => state.player.playing,
isLoadingAudio: state => state.player.isLoadingAudio,
volume: state => state.player.volume,
looping: state => state.player.looping,
duration: state => state.player.duration,
bufferProgress: state => state.player.bufferProgress,
errored: state => state.player.errored,
currentTime: state => state.player.currentTime,
queue: state => state.queue
}),
...mapGetters({
currentTrack: 'queue/currentTrack',
hasNext: 'queue/hasNext',
hasPrevious: 'queue/hasPrevious',
emptyQueue: 'queue/isEmpty',
durationFormatted: 'player/durationFormatted',
currentTimeFormatted: 'player/currentTimeFormatted',
progress: 'player/progress'
}),
updateProgressThrottled () {
return _.throttle(this.updateProgress, 50)
},
labels () {
const audioPlayer = this.$pgettext('Sidebar/Player/Hidden text', 'Media player')
const previous = this.$pgettext('Sidebar/Player/Icon.Tooltip', 'Previous track')
const play = this.$pgettext('Sidebar/Player/Icon.Tooltip/Verb', 'Play')
const pause = this.$pgettext('Sidebar/Player/Icon.Tooltip/Verb', 'Pause')
const next = this.$pgettext('Sidebar/Player/Icon.Tooltip', 'Next track')
const unmute = this.$pgettext('Sidebar/Player/Icon.Tooltip/Verb', 'Unmute')
const mute = this.$pgettext('Sidebar/Player/Icon.Tooltip/Verb', 'Mute')
const expandQueue = this.$pgettext('Sidebar/Player/Icon.Tooltip/Verb', 'Expand queue')
const loopingDisabled = this.$pgettext('Sidebar/Player/Icon.Tooltip',
'Looping disabled. Click to switch to single-track looping.'
)
const loopingSingle = this.$pgettext('Sidebar/Player/Icon.Tooltip',
'Looping on a single track. Click to switch to whole queue looping.'
)
const loopingWhole = this.$pgettext('Sidebar/Player/Icon.Tooltip',
'Looping on whole queue. Click to disable looping.'
)
const shuffle = this.$pgettext('Sidebar/Player/Icon.Tooltip/Verb', 'Shuffle your queue')
const clear = this.$pgettext('Sidebar/Player/Icon.Tooltip/Verb', 'Clear your queue')
const addArtistContentFilter = this.$pgettext('Sidebar/Player/Icon.Tooltip/Verb', 'Hide content from this artist…')
return {
audioPlayer,
previous,
play,
pause,
next,
unmute,
mute,
loopingDisabled,
loopingSingle,
loopingWhole,
shuffle,
clear,
expandQueue,
addArtistContentFilter
}
}
},
watch: {
currentTrack: {
async handler (newValue, oldValue) {
if (newValue === oldValue) {
return
}
this.nextTrackPreloaded = false
clearTimeout(this.playTimeout)
if (this.currentSound) {
this.currentSound.pause()
}
this.$store.commit('player/isLoadingAudio', true)
this.playTimeout = setTimeout(async () => {
await this.loadSound(newValue, oldValue)
}, 100)
this.updateMetadata()
},
immediate: false
},
volume: {
immediate: true,
handler (newValue) {
this.sliderVolume = newValue
Howler.volume(toLinearVolumeScale(newValue))
}
},
sliderVolume (newValue) {
this.$store.commit('player/volume', newValue)
},
playing: async function (newValue) {
if (this.currentSound) {
if (newValue === true) {
this.soundId = this.currentSound.play(this.soundId)
} else {
this.currentSound.pause(this.soundId)
}
} else {
await this.loadSound(this.currentTrack, null)
}
this.observeProgress(newValue)
},
currentTime (newValue) {
if (!this.isUpdatingTime) {
this.setCurrentTime(newValue)
}
this.isUpdatingTime = false
},
emptyQueue (newValue) {
if (newValue) {
Howler.unload()
}
}
}
}
</script>

View File

@ -1,12 +1,57 @@
import Vue from 'vue'
import Vuex from 'vuex'
import EmbedFrame from './EmbedFrame'
import locales from '@/locales'
import player from '@/store/player'
import queue from '@/store/queue'
import instance from '@/store/instance'
import GetTextPlugin from 'vue-gettext'
Vue.config.productionTip = false
//Vue.config.productionTip = false
Vue.use(Vuex)
const store = new Vuex.Store({
modules: {
player,
queue,
instance
}
})
let availableLanguages = (function () {
let l = {}
locales.locales.forEach(c => {
l[c.code] = c.label
})
return l
})()
let defaultLanguage = 'en_US'
//if (availableLanguages[store.state.ui.currentLanguage]) {
// defaultLanguage = store.state.ui.currentLanguage
//}
Vue.use(GetTextPlugin, {
availableLanguages: availableLanguages,
defaultLanguage: defaultLanguage,
// cf https://github.com/Polyconseil/vue-gettext#configuration
// not recommended but this is fixing weird bugs with translation nodes
// not being updated when in v-if/v-else clauses
autoAddKeyAttributes: true,
languageVmMixin: {
computed: {
currentKebabCase: function () {
return this.current.toLowerCase().replace('_', '-')
}
}
},
translations: {},
silent: true
})
/* eslint-disable no-new */
new Vue({
el: '#app',
store,
render (h) {
return h('EmbedFrame')
},