javascript 我可以使用 Angular 变量作为音频标签的来源吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23659395/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 01:19:43  来源:igfitidea点击:

Can I use Angular variables as the source of an audio tag?

javascriptangularjsaudioangularjs-directiveangularjs-ng-repeat

提问by Hols

I am trying to do the following:

我正在尝试执行以下操作:

<div ng-repeat="audio in event.audios">
    <audio ng-src="/data/media/{{audio}}" controls></audio>
</div>

But when I load the view, the {{audio}} variable is not parsed but hardcoded into the source as is. However, if for example, I place that same variable outside of the audio tag it renders the name of the audio file correctly. I've tried using both src and ng-src to no avail.

但是当我加载视图时,{{audio}} 变量没有被解析而是硬编码到源中。但是,例如,如果我将相同的变量放在音频标签之外,它会正确呈现音频文件的名称。我试过同时使用 src 和 ng-src 无济于事。

Is there a way to get the variable to work within an audio tag?

有没有办法让变量在音频标签中工作?

Thanks in advance.

提前致谢。

回答by Joe

I'm not all thatfamiliar with the ngSrc directive outside of using it on images, but it might require an img tag somewhere in the source.

我不是所有熟悉使用它在图像的ngSrc指令之外,但它可能需要在源img标签的地方。

Try this:

<div ng-repeat="audio in event.audios">
    <audio ng-attr-src="/data/media/{{audio}}" controls></audio>
</div>

试试这个:

<div ng-repeat="audio in event.audios">
    <audio ng-attr-src="/data/media/{{audio}}" controls></audio>
</div>

The ng-attr- directive can be used for any attribute that doesn't have a specific role in angular. You can read more about it on this page.

ng-attr- 指令可用于任何在 angular 中没有特定角色的属性。您可以在此页面上阅读更多相关信息。

Update, I was wrong.

更新,我错了。

I created a jsfiddle and found the actual error that was occurring.

我创建了一个 jsfiddle 并找到了正在发生的实际错误。

You're getting an error from the sce service. See the SO question here.

您从 sce 服务收到错误消息。请参阅此处的 SO 问题。

The solution is to use $sce.trustAsResourceUrl().

解决方案是使用$sce.trustAsResourceUrl().

Example:

例子:

angular.module('AudioTest', [])
.controller('AudioTestCtrl', function($scope, $sce) {
    $scope.event = { 'audios': [
        $sce.trustAsResourceUrl('/data/media/test1'),
        $sce.trustAsResourceUrl('/data/media/test2')
    ]};
});

Here's the fiddle.

这是小提琴

Update #2

更新 #2

If you don't want to set the url as hard coded or loop through after you get a response from the server, you can use a custom filter to accomplish what you're looking for. This method does not use interpolation, which is where the error is being thrown.

如果您不想在收到服务器响应后将 url 设置为硬编码或循环,您可以使用自定义过滤器来完成您要查找的内容。此方法不使用插值,这是抛出错误的地方。

JS:

JS:

angular.module('AudioTest', [])
.filter('trustedAudioUrl', function($sce) {
    return function(path, audioFile) {
        return $sce.trustAsResourceUrl(path + audioFile);
    };
})
.controller('AudioTestCtrl', function($scope) {
    $scope.event = { 'audios': ['test1', 'test2']};
});

HTML:

HTML:

<div ng-app="AudioTest">
    <div ng-controller="AudioTestCtrl">
        <div ng-repeat="audio in event.audios">
            <audio ng-src="/data/media/ | trustedAudioUrl:audio)" controls></audio>
        </div>
    </div>
</div>

And the new fiddle.

新小提琴

回答by Hols

Ok, thanks to theJoeBiz's input and some thinking around I solved this by making a directive, here is the code:

好的,感谢 theJoeBiz 的输入和一些思考,我通过制定指令解决了这个问题,这是代码:

app.directive('audios', function($sce) {
  return {
    restrict: 'A',
    scope: { code:'=' },
    replace: true,
    template: '<audio ng-src="{{url}}" controls></audio>',
    link: function (scope) {
        scope.$watch('code', function (newVal, oldVal) {
           if (newVal !== undefined) {
               scope.url = $sce.trustAsResourceUrl("/data/media/" + newVal);
           }
        });
    }
  };
});

Then on the template I used it like so:

然后在模板上我像这样使用它:

<div ng-repeat="audio in event.audios">
    <div audios code="audio"></div>
</div>

It is all working fine now.

现在一切正常。

回答by Plato

Hey FWIW i found this page looking for a solution to template URL's for my audio tag. However I am using multiple source tags for cross browser support:

嘿 FWIW 我发现这个页面正在寻找我的音频标签模板 URL 的解决方案。但是我使用多个源标签来支持跨浏览器:

<audio id="myAudioTag">
  <source ng-src="{{sceSoundUrlMp3}}">
  <source ng-src="{{sceSoundUrlOgg}}">
</audio>

First I solved SCE issues by whitelisting *.ogg, *.mp3: (keep 'self' otherwise your future requests fail)

首先,我通过将 *.ogg、*.mp3 列入白名单解决了 SCE 问题:(保留“自我”,否则您以后的请求会失败)

.config(function($sceDelegateProvider) {
  $sceDelegateProvider.resourceUrlWhitelist([
    "self",
    /(mp3|ogg)$/,
  ]);
})

This stopped giving SCE errors but Firefox reported 'no source' and didn't notice the srctag angular added.

这停止了​​ SCE 错误,但 Firefox 报告“无源”并且没有注意到src添加的标签角度。

The last step was to call load on the element after trusting and setting $scope.sceSoundUrlMp3: $('#myAudioTag')[0].load()

最后一步是在信任和设置后在元素上调用 load $scope.sceSoundUrlMp3$('#myAudioTag')[0].load()

回答by MFahad

I have used $sce.trustAsResourceUrl("/data/media/" + newVal)but it didn't work for.What seemed to work for me was to put document.getElementById('player').src = {{url}}in the controller

我用过,$sce.trustAsResourceUrl("/data/media/" + newVal)但没有用。似乎对我有用的是放入 document.getElementById('player').src = {{url}}控制器

Hope that helps someone else

希望能帮助别人