Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Coffeescript conversion of peepcode-tunes for angularjs
class @TunesCtrl
constructor:($xhr)->
@player = @$parent.$new Player
$xhr 'GET', 'albums.json', (statusCode, body)=>
@albums = body
TunesCtrl.$inject = ['$xhr']
class @Player
constructor:(@$audio)->
@paused = false
@current = album:0, track:0
@playlist = []
@playing = false
@playlist.add = (album)=>
if angular.Array.indexOf(@playlist, album) != -1
return
@playlist.push album
@playlist.remove = (album)=>
if angular.Array.indexOf(@playlist, album) == @current.album
@reset()
angular.Array.remove(@playlist, album)
@$audio.addEventListener 'ended', (=>
@$parent.$apply @next
), false
play:(track, album)->
unless @playlist.length
return
if angular.isDefined(track)
@current.track = track
if angular.isDefined(album)
@current.album = album
unless @paused
@$audio.src = @playlist[@current.album].tracks[@current.track].url
@$audio.play()
@playing = true
@paused = false
pause:()->
if @playing
@$audio.pause()
@playing = false
@paused = true
reset:()->
@pause()
@current.album = 0
@current.track = 0
next: ()->
unless @playlist.length
return
@paused = false
if @playlist[@current.album].tracks.length > (@current.track + 1)
@current.track++
else
@current.track = 0
@current.album = (@current.album + 1) % @playlist.length
if @playing
@play()
previous:()->
unless @playlist.length
return
@paused = false
if @current.track > 0
@current.track--
else
@current.album = (@current.album - 1 + @playlist.length) % @playlist.length
@current.track = @playlist[@current.album].tracks.length - 1
if @playing
@play()
Player.$inject = ['audio']
angular.service 'audio', ($document)->
$document[0].createElement('audio')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment