How do I control an HTML5 audio player with AngularJS?
angularjs, angularjs-directive, dom-events, javascript
Solution
I've build a html player backended by flash to play music, so build my own event flow to to the operations, but I think that the best way is to write an directive to do that. In this case you can re-use the directive if you need to and it works very well.
If you have the player object into your directive, you can catch all events normally.
Take a look on this website: Angular Tunes and check out the sources to see what he does. It's the same as you trying to do.
I hope it helps.
Problem
I have a simple implementation in JavaScript that plays songs from a playlist continuously until it ends. I have not been able to find which is the proper way to implement it in AngularJS. This exercise should address the desired features: - Encapsulate player as a service - Do I need to use directives to access the control? - Catch the "end" event to start the new song Here is an excerpt of the HTML file. ``` ... <div class="span4"> <button class="btn btn-large btn-primary" type="button" ng-click="startPlaying();">Start Playing</button> </div> ... <div class="span6"> <h4 id="NowPlayingID">Now Playing: </h4> <audio id="AudioPlayerID" controls="controls"> </audio> </div> ... <!-- OLD JavaScript code --> <script type="text/javascript"> function playNextSong(player) { if (playlist.currentSongIX >= playlist.songs.length) return; $('#NowPlayingID').text('Now Playing: ' + playlist.songs[playlist.currentSongIX].name); player.src = playlist.songs[playlist.currentSongIX].path; player.play(); playlist.currentSongIX++; } function startPlaying() { var player = document.getElementById("AudioPlayerID"); player.addEventListener('ended', function() { playNextSong(player); }, false); playNextSong(player); }; </script> ``` The following code is work in progress and incomplete: ``` app.controller('PlayCtrl', function($scope, $routeParams, Playlist, $log, $document) { $scope.playlist = Playlist.get({playlistID:$routeParams.playlistID}); var player = ????? ("AudioPlayerID"); $scope.startPlaying = function () { angular.forEach($scope.playlist.songs, function(song) { $log.log("Playing: " + song.name); player.src = song.path; player.play(); }); }; }); ``` ... My questions are: - Which is the proper way to access the audio player? - Do I need to use directives? - How do I catch the 'end' event?