AngularJS:音频预览上的播放/静音按钮

时间:2017-06-02 19:25:37

标签: javascript angularjs audio

我目前正在尝试为音乐家创建一个网站,他希望在网站上对他的专辑歌曲进行小型预览。

我现在有一个JSON数组,其中包含我加载到AngularJS并加载到页面上的歌曲的名称

<tr ng-repeat="song in info.songs">
        <td>
          <a href="" ng-click='startPlayback(song.url)' class="play-symbol"><span class="glyphicon glyphicon-headphones" aria-hidden="true"></a>
          <a href="" ng-click='stopPlayback()' class="stop-symbol"><span class="glyphicon glyphicon-volume-off" aria-hidden="true"></a>
        </td>
        <td>{{song.title}}</td>
        ...
 </tr>

正如你所看到的,我还创建了一个&#34; startPlayback&#34;和&#34; stopPlayback&#34;这正是它所说的。

我现在的问题是我只想要&#34; glyphicon-headphones&#34;一开始就显示的符号,当我开始播放时,我开始播放的歌曲中的耳机改为&#34; glyphicon-volume-off&#34;符号。 我已经走到了这一步,但现在我遇到了问题:

我想要它,以便您现在可以点击任何其他耳机(&#34;开始&#34;)图标,播放停止播放(我也已经有了),来自&#34;的静音符号老&#34;播放的歌曲改回耳机和#34;新的&#34;符号更改为静音符号。

你会如何实现这样的目标?

1 个答案:

答案 0 :(得分:2)

我认为您可以使用ngClass directive使用当前正在播放的歌曲的状态来动态切换css类。 不知道控制器中的代码究竟是怎样的, 但希望我的想法会对你有所帮助。因此,对于标记,您可以使用类似的东西(如果您关心性能,则为good practice to use track by for repeaters and one time bindings):

<tr ng-repeat="song in info.songs track by song.id">
        <td>
          <a href="javascript:void(0)" ng-click='togglePlayback(song, info.songs)' class="play-symbol" ng-class="{'play-symbol' : !song.isPlaying, 'stop-symbol': song.isPlaying}">
            <span class="glyphicon" aria-hidden="true" ng-class="{'glyphicon-headphones' : !song.isPlaying, 'glyphicon-volume-off': song.isPlaying}"></span>
          </a>
        </td>
        <td>{{::song.title}}</td>
        ...
 </tr>

在控制器中你可以使用方法来切换被点击的歌曲的状态:

 $scope.togglePlayback = function(song, songs){
    //set "stopped" css class for all songs except the one was clicked
    angular.forEach(songs, function(s){
        if (s.id != song.id) {
            s.isPlaying = false;
        }
    });

    //toggle the song was clicked
    song.isPlaying = !song.isPlaying;

    //some you code to start/stop playback depending on the song.isPlaying value
    //...

 }

希望这会对你有所帮助。