【问题标题】:angular does not change audio source from json角度不会改变来自json的音频源
【发布时间】:2016-05-17 08:50:02
【问题描述】:

我正在尝试将音频文件嵌入到带有音频标签的 HTML 中。播放音频的 src 是从 API 获得的,我有 5-6 个不同的音频文件。

当我点击 playStart() 时,播放的音频文件是相同的,即使 src 显示不同的链接

<tbody>
    <tr ng-repeat="val in values track by $index">
        <td ng-bind="$index +1">1</td>
        <td ng-bind="val._id">ED1500322</td>
        <td>
            <audio id="audioTag">
                <source controls ng-src="{{val.file}}"></source>
            </audio>

            <button class="play-btn" ng-click="playStart()"><img src="app_static/images/play.png"></button>
            <button class="play-btn" ng-click="playStop()">stop</button>
        </td>
        <td ng-bind="val.result"></td>

    </tr>
</tbody>

js文件

$scope.playStart = function() {
    var audio = document.getElementById("audioTag");
    audio.load();
    audio.play();

};

$scope.playStop = function() {
    var audio = document.getElementById("audioTag");
    audio.pause();
    audio.currentTime = 0;
};

即使 DOM 显示链接不同,我也只能听到相同的音频片段

对于播放从 api 获得的音乐的任何帮助表示赞赏

【问题讨论】:

  • 使用类,因为 getElementById 总是返回元素的第一个 id

标签: javascript angularjs json audio


【解决方案1】:

使用类:

HTML

<tbody>
<tr ng-repeat="val in values track by $index">
    <td ng-bind="$index +1">1</td>
    <td ng-bind="val._id">ED1500322</td>
    <td>
        <audio class="audioTag">
            <source controls ng-src="{{val.file}}"></source>
        </audio>

        <button class="play-btn" ng-click="playStart($index)"><img src="app_static/images/play.png"></button>
        <button class="play-btn" ng-click="playStop($index)">stop</button>
    </td>
    <td ng-bind="val.result"></td>

</tr>

JS

$scope.playStart = function(index_) {
    var audio = document.getElementsByClassName("audioTag")[index_];
    audio.load();
    audio.play();

};

$scope.playStop = function() {
    var audio = document.getElementsByClassName("audioTag")[index_];
    audio.pause();
    audio.currentTime = 0;
};

【讨论】:

    【解决方案2】:

    你的问题是

     document.getElementById("audioTag")
    

    总是返回页面中的第一个元素。

    你可以做的是改变id,这样每个音频元素都会有不同的id。

    改变

    <audio id="audioTag">
    

     <audio id="audioTag{{$index}}">
    

    所以元素会有标签“audioTag1”、“audioTag2”。

    之后,将对playStartplayStop 函数的调用更改为:

    playStart('audioTag{{$index}}')
    

    所以你会得到 id 作为参数。

    你的功能变成:

    $scope.playStart = function(id) {
        var audio = document.getElementById(id);
        audio.load();
        audio.play();  
    };
    

    就是这样。

    【讨论】:

      猜你喜欢
      • 2014-09-11
      • 2013-03-25
      • 2016-02-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-10
      • 1970-01-01
      相关资源
      最近更新 更多