我有一些人们可以听的小样本 mp3 文件,并用 angularjs 制作了一个小播放器。 单击播放图像时,将播放音频,并通过更改图像的类别将播放图像更改为暂停图像。
我希望当音频停止播放时图像变回来
这是 html:
<table class="loops">
<thead>
<tr>
<th ng-if="domein() == 'localhost' || domein() == 'basles.be'" class='tien weg'>Luister</th>
<th ng-if="domein() == 'basslessons.be'" class='tien weg'>Listen</th>
<th>Type</th>
<th ng-if="domein() == 'localhost' || domein() == 'basles.be'" class='beschrijving'>Beschrijving</th>
<th ng-if="domein() == 'basslessons.be'" class='beschrijving'>Description</th>
<th class='tien'>Tempo</th>
<th class='tien'>Download</th>
</tr>
</thead>
<tr ng-animate="'animate'" ng-repeat="item in loops | filter: query | orderBy: sorteren:direction">
<td>
<img ng-class="class" ng-alt="play Button" height="25px" width="25px" ng-click="playTrack(item.loop_id)">
</td>
<td class="info" ng-if="item.loop_cat == 1">Drum Loop</td>
<td class="info" ng-if="item.loop_cat == 2">Backing Track</td>
<td class="info">{{item.beschrijving_nl}}</td>
<td class="bpm">{{item.loop_bpm}} BPM</td>
<td><a ng-href="loops/loops.php?serve={{item.loop_link}}"><img src="images/download.png" width="30" height="30" alt="Download WAV" /></a></td>
</tr>
Angularjs
myApp.controller('myLoopController', ['$scope', '$http', '$window', function ($scope, $http, $window) {
$http.get('js/loops.json').success(function (data) {
// some other code
$scope.class = "playButton play";
$scope.afspelen = false;
$scope.audio = new Audio();
$scope.playTrack = function (file) {
if(!$scope.afspelen) {
$scope.audio.src = 'loops/' + file + '-myFile.mp3';
$scope.audio.play();
$scope.class = "playButton pause";
$scope.afspelen = true;
} else {
$scope.audio.src = 'loops/' + file + '-myFile.mp3';
$scope.audio.pause();
$scope.class = "playButton play";
$scope.afspelen = false;
}
}
$scope.audio.addEventListener('ended', function(){
$scope.class = "playButton play";
$scope.afspelen = false;
console.log("ended ");
});
});
}]);
控制台输出“结束”,但类不会变回“playButton play”。知道为什么吗?
(我的代码可能还有很多需要改进的地方,我刚刚开始使用 angularjs,此时我只想让它工作)
提前谢谢您!
最佳答案
如果您在 Angular 上下文之外执行任何操作(例如监听 DOM 事件),则需要调用 $scope.$apply() (例如您的监听器 $scope.audio.addEventListener('end '...)).
所以在你的代码中:
$scope.audio.addEventListener('ended', function(){
$scope.class = "playButton play";
$scope.afspelen = false;
$scope.$apply(); // <<<<
console.log("ended ");
});
关于Angularjs:更改音频类别已结束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34556587/