如何在AngularJS中播放声音

14

使用API获取要在音频标签中播放的声音的URL
查看

<img src="../img/play.svg" alt="Play" ng-click="playSound('exampleWord')" width="48"/>

控制器:

$scope.playSound=function(input){
    $scope.audio={};
    soundFetch.getSound(input).success(function(data){
        $scope.audio=data;
    });
}

soundFetch是调用getSound函数的服务。返回的数据是歌曲的URL。 我如何在点击img标签后播放声音。当前出现错误Error: [$interpolate:interr]

ng-click="playSound(word)",从{{word}}中删除{{xx}}。 - PSL
@PSL 我已经尝试了任何单词,但它仍然无法工作。 - Akansh
这里有一个很好的答案:https://dev59.com/4n_aa4cB1Zd3GeqP6bDy 希望能帮到你。 - Kirill Husiatyn
4个回答

32
    $scope.playAudio = function() {
        var audio = new Audio('audio/song.mp3');
        audio.play();
    };

1
var playSound = function(mp3File){
  var audioElement = document.createElement('audio');
  audioElement.setAttribute('src', "/sound/"+mp3File);
  audioElement.play();
}

0

看起来playSound函数以参数形式接受输入

我会尝试

ng-click="playSound(this)" 或者在按钮情况下

ng-click="playSound(document.getElementById('audio'))"


0
  var audioFile = new Audio($scope.audioUrl); 
            audioFile.play();  //we can not get metadata until audio is fetched
            audioFile.pause(); //as soon as audio playes it pause so user does not hear a sound 

 audioFile.onplay = function () {
                audioFile.preload("metadata");         
            };

            audioFile.onloadedmetadata = function () {
                console.log(audioFile.duration);
                $scope.audioDuration = audioFile.duration;
            };

当调用音频播放方法时,元数据会被加载。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接