@SteveOC 64 的方法处理创建音频的新实例。如果您已经有一个音频标签,例如
<audio id="audio" controls></audio>
你可以试试下面的代码
app.factory('audio', function($document) {
var audioElement = $document[0].getElementById('audio');
audioElement.autoPlay = true; // as per your requirement
return {
audioElement: audioElement,
play: function(filename) {
audioElement.src = filename;
audioElement.play();
},
resume: function() {
audioElement.play();
},
pause: function() {
audioElement.pause();
},
stop: function() {
audioElement.pause();
audioElement.src = audioElement.currentSrc; /** http://stackoverflow.com/a/16978083/1015046 **/
},
incVol: function() {
if (audioElement.volume < 1) {
audioElement.volume = (audioElement.volume + 0.1).toFixed(2);
}
return audioElement.volume;
},
decVol: function() {
if (audioElement.volume > 0) {
audioElement.volume = (audioElement.volume - 0.1).toFixed(2);
}
return audioElement.volume;
},
timer: function(callback) {
audioElement.ontimeupdate = function() {
callback(audioElement.duration, audioElement.currentTime)
};
},
}
});
在注入audio
工厂后在您的控制器中,您可以将其称为
audio.play('/api/resource?resource=' + uri);
如果这是一个事件驱动的,例如在单击另一个元素时播放音频
$scope.$apply(function() {
$scope.audioPlayer = true;
audio.play('/api/resource?resource=' + uri);
$scope.isAudioPlaying = true;
});
如果有人正在寻找视频工厂:
HTML
<video id="video" controls></video>
工厂
app.factory('video', function($document) {
var videoElement = $document[0].getElementById('video');
videoElement.autoPlay = true;
return {
videoElement: videoElement,
play: function(filename) {
videoElement.src = filename;
videoElement.play();
},
resume: function() {
videoElement.play();
},
pause: function() {
videoElement.pause();
},
stop: function() {
videoElement.pause();
videoElement.src = videoElement.currentSrc; /** http://stackoverflow.com/a/16978083/1015046 **/
},
incVol: function() {
if(videoElement.volume < 1) {
videoElement.volume = (videoElement.volume + 0.1).toFixed(2);
}
return videoElement.volume;
},
decVol: function() {
if(videoElement.volume > 0) {
videoElement.volume = (videoElement.volume - 0.1).toFixed(2);
}
return videoElement.volume;
},
timer: function(callback) {
videoElement.ontimeupdate = function() {
callback(videoElement.duration, videoElement.currentTime)
};
},
}
});
您可以将其调用为video.play('/api/resource?resource=' + uri);
希望这可以帮助!