Skip to content

Instantly share code, notes, and snippets.

@Sigmus
Last active December 14, 2015 08:48
Show Gist options
  • Save Sigmus/5059977 to your computer and use it in GitHub Desktop.
Save Sigmus/5059977 to your computer and use it in GitHub Desktop.
define [
'backbone',
'models/recording'
'config'
],
(Backbone, RecordingModel, Config) ->
status = 'stopped'
#
# Interval to display current time of the recording.
#
monitor = null
#
# Current RecordingModel.
#
current = null
isStatus = (statusName, set) ->
status = statusName if set
return status == statusName
Backbone.Collection.extend
model: RecordingModel
#
# Return or set status.
#
isStopped: _.partial isStatus, 'stopped'
isPaused: _.partial isStatus, 'paused'
isPlaying: _.partial isStatus, 'playing'
isFinished: _.partial isStatus, 'finished'
initialize: ->
@on 'player:start', => @startMonitor()
@on 'player:stop', => @stopMonitor()
@on 'player:end', => @next()
@on 'player:loading', =>
@stopMonitor()
current.set 'loading', 'true' if current != null
@on 'add', (recording) =>
recording.index = @size() - 1
@start 0 if @length == 1 # Autoplay
isCurrent: (recording) ->
current != null and current.get('id') == recording.get('id')
#
# Start nxext track. If it's last, restart playlist.
#
next: ->
if current.index + 1 == @models.length
newIndex = 0
else
newIndex = current.index + 1
@pause()
@start newIndex
#
# Start now or delegate if player isn't ready yet.
#
start: (pos) ->
if @player.isReady()
@loadOrPlay @models[pos]
else
@on 'player:ready', => @loadOrPlay @models[pos]
loadOrPlay: (recording) ->
if @isCurrent(recording)
@player.play()
else
@player.load recording
current = recording
@isPlaying true
resume: ->
@player.play()
@isPlaying true
pause: ->
@player.pause()
@isStopped true
startMonitor: ->
current.set 'loading', 'false'
monitor = setInterval _.bind(@updateTime, @), Config.monitorCycle
stopMonitor: -> clearInterval monitor if monitor
seekToFraction: (f) ->
@pause()
@player.seekToFraction(f)
@resume()
updateTime: ->
current.set
'time': ms_to_min(@player.time() * 1000)
'duration': ms_to_min(@player.duration() * 1000)
'percentage': @player.percentage()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment