Attempt to preload the next song (resolves #232)

This commit is contained in:
An Phan 2016-03-06 16:19:37 +08:00
parent caff687bdd
commit 2d08223106
2 changed files with 34 additions and 2 deletions

View file

@ -1,7 +1,6 @@
import _ from 'lodash';
import $ from 'jquery';
import sharedStore from '../stores/shared';
import queueStore from '../stores/queue';
import songStore from '../stores/song';
import artistStore from '../stores/artist';
@ -60,6 +59,26 @@ export default {
this.playNext();
});
/**
* Attempt to preload the next song if the current song is about to end.
*/
document.querySelector('.plyr').addEventListener('timeupdate', e => {
if (!this.player.media.duration || this.player.media.currentTime + 10 < this.player.media.duration) {
return;
}
// The current song has only 10 seconds left to play.
var nextSong = queueStore.getNextSong();
if (!nextSong || nextSong.preloaded) {
return;
}
var $preloader = $('<audio>');
$preloader.attr('src', songStore.getSourceUrl(nextSong));
nextSong.preloaded = true;
});
/**
* Listen to 'input' event on the volume range control.
* When user drags the volume control, this event will be triggered, and we
@ -107,7 +126,7 @@ export default {
// Manually set the `src` attribute of the audio to prevent plyr from resetting
// the audio media object and cause our equalizer to malfunction.
this.player.media.src = `${sharedStore.state.cdnUrl}api/${song.id}/play?jwt-token=${ls.get('jwt-token')}`;
this.player.media.src = songStore.getSourceUrl(song);
$('title').text(`${song.title}${config.appTitle}`);
$('.plyr audio').attr('title', `${song.album.artist.name} - ${song.title}`);

View file

@ -5,9 +5,11 @@ import http from '../services/http';
import utils from '../services/utils';
import stub from '../stubs/song';
import favoriteStore from './favorite';
import sharedStore from './shared';
import userStore from './user';
import albumStore from './album';
import artistStore from './artist';
import ls from '../services/ls';
export default {
stub,
@ -362,6 +364,17 @@ export default {
return originalSong;
},
/**
* Get a song's playable source URL.
*
* @param {Object} song
*
* @return {string} The source URL, with JWT token appended.
*/
getSourceUrl(song) {
return `${sharedStore.state.cdnUrl}api/${song.id}/play?jwt-token=${ls.get('jwt-token')}`;
},
/**
* Get the last n recently played songs.
*