3

Any idea on how to tie an audio element to an ng-model?

I'd like to update a div with the value of the playback of an audio element?

<audio ng-model="myAudio">...</audio>
<div>{{myAudio.timeElapsed}}</div>

Or something like that. Any idea how to do that?

Gabriele Petrioli
  • 191,379
  • 34
  • 261
  • 317
mkhatib
  • 5,089
  • 2
  • 26
  • 35
  • Simple code worked for me [posted as answer][1] [1]: http://stackoverflow.com/questions/15485768/changing-html5s-source-src-attribute-takes-no-effect-wtih-angularjs/32579152#32579152 – Swapnil Chincholkar Sep 15 '15 at 06:32

2 Answers2

4

You can do this by creating a custom directive for your app. The directive binds a function to the timeupdate event of your audio element. The bound function updates the timeElapsed property of the current scope and calls $apply to propagate changes to the view. You can see an example at:

http://jsfiddle.net/ASjRP/20/

HTML

<body ng-app="audio" ng-controller="TestAudioCtrl">
    <audio controls my-audio>
        <source src="**YOUR SOURCE FILE**"></source>
    </audio>
    <div>Elapsed: {{timeElapsed}}</div>
</body>

Javascript

angular.module("audio", [])
    .directive("myAudio", function(){
        return function(scope, element, attrs){
            element.bind("timeupdate", function(){
                scope.timeElapsed = element[0].currentTime;
                scope.$apply();
            });
        }
    });

TestAudioCtrl = function($scope){
    $scope.timeElapsed = 0;
}
narced133
  • 712
  • 4
  • 7
  • Note, I'm just getting started with Angular myself. Please tell me if there's a more idiomatic way to handle this. – narced133 Jul 12 '13 at 21:48
  • I don't know what is most idiomatic, but this can be done even more simply by defining a timeElapsed() method in your controller and referencing it from html. You don't need ng-model at all as long as the controller is in scope. – Phil Mitchell Aug 16 '13 at 23:47
0

I seriously recommend use of the HTML5 Audio API for an robust player with some real flexibility. I developed mine from scratch:

https://gist.github.com/djvs/24006c975ff11fd889e3

The standard browser controls for HTML5 audio generally suck, and also often break when you attempt to tie them into something like ng-model or interpolation for sources, in my experience...

djvs
  • 552
  • 2
  • 11