更改html5的源"src"属性对angularjs没有任何影响

use*_*431 29 html5-audio angularjs

我有一个音频文件列表,显示为链接和一个<audio>html5播放器.每个链接调用一个函数,该函数在以下内容中更改<source>标记的src <audio>:

<audio controls="controls" preload="none">
  <source type="audio/mpeg" src="{{selectedSongPath}}"/>
</audio>
Run Code Online (Sandbox Code Playgroud)

...

<div class="songEntry" ng-repeat="song in songs">
  <a href="" ng-click="songSelect(song.path)">{{song.name}}</a>
</div>
Run Code Online (Sandbox Code Playgroud)

...

$scope.songSelect = function(songPath) {
    $scope.selectedSongPath = songPath;
}
Run Code Online (Sandbox Code Playgroud)

我可以看到src正在改变,但没有播放.路径还可以; 如果我用其中一条路径初始化src,则播放器可以工作.

我究竟做错了什么?

Ste*_* 64 25

这是一些有角度的方法:

1)使用ng-src =而不是src =

角度文档解释了为什么这有效:http://docs.angularjs.org/api/ng.directive : ngSrc

在编译阶段,angular将扩展元素以包含正确的src =属性.

这将改变HTML5音频元素的src属性,但不幸的是,这还不足以制作新的歌曲.你需要通过调用.play()方法来促使音频元素做某事.

糟透了:(

进一步黑客沿着这条路径建议在控制器内部进行DOM操作.这通常表明这是错误的解决方案.

更好的解决方案是使用服务!

2)使用角度服务的音频

// Define a simple audio service 
mpApp.factory('audio',function ($document) {
  var audioElement = $document[0].createElement('audio'); // <-- Magic trick here
  return {
    audioElement: audioElement,

    play: function(filename) {
        audioElement.src = filename;
        audioElement.play();     //  <-- Thats all you need
    }
    // Exersise for the reader - extend this service to include other functions
    // like pausing, etc, etc.

  }
});
Run Code Online (Sandbox Code Playgroud)

现在,在您的控制器中,您可以注入"音频",并做任何您需要做的事情.

例如:

function myAstoundingAudioCtrl($scope, audio) { //<-- NOTE injected audio service

    $scope.songSelect = function(songPath) {
        audio.play(songPath);    //     <---  Thats All You Need !
    }
}
Run Code Online (Sandbox Code Playgroud)

您现在可以将"audio"作为参数添加到任何需要能够更改音乐的控制器,并使用此处定义的相同API调用.

作为"服务",整个应用程序只有一个实例.所有对"audio"的调用都指向同一个对象.这对于角度的所有服务都是如此.正是在这种情况下我们需要的.

该服务在应用程序的根文档上创建一个不可见的HTML5元素,因此无需在任何地方的视图上添加标记.这具有在用户导航到不同视图的同时保持歌曲播放的额外好处.

有关$ document服务的定义,请参阅 http://docs.angularjs.org/api/ng.$ document.

希望有助于交配:)

  • 这是一个很好的解决方案.我很感激你已经解释了它最终如何运作!最佳答案 (2认同)

Ora*_*Dar 19

即使在使用$ sce.trustAsResourceUrl之后我也遇到了同样的问题,然后我意识到问题出在HTML上.源应该放在音频标签本身:

<audio controls data-ng-src="{{yourTrustedUrl}}" ></audio>
Run Code Online (Sandbox Code Playgroud)

  • 很抱歉说“我也是”,但我真的很想感谢你。我花了很多时间在这个问题上并变得疯狂。 (2认同)

Rah*_*kla 5

<audio ng-src="{{getAudioUrl()}}" audioplayer controls></audio>

$scope.getAudioUrl = function() {
return $sce.trustAsResourceUrl('your url');
};
Run Code Online (Sandbox Code Playgroud)

这对我有用,你需要对你进行补充


Cai*_*nha 0

从未尝试过使用audio标签,但src应该进行插值,所以它应该在{{}}.

<audio controls="controls" preload="none">
  <source type="audio/mpeg" src="{{selectedSongPath}}"/>
</audio>
Run Code Online (Sandbox Code Playgroud)

你已经尝试过这个了吗?