daG
daG

Reputation: 55

AngularJS: Play/Mute button on audio previews

I am currently trying to make a website for a musician and he wants to have small previews of his songs of his album on the website.

I now have a JSON array with the names of the songs that I load into AngularJS and load onto the page with

<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>

As you can see I also created a "startPlayback" and "stopPlayback" which does exactly what it says.

My problem now is that I want only the "glyphicon-headphones" symbol to show up at the beginning, when I start the playback ONLY the headphone at the song I started playing changes to the "glyphicon-volume-off" symbol. I already got this far, but now I run into the problem:

I want it, so that you can now click on any other headphone("start") icon, the playback stops playing (I also already got that), the mute symbol from the "old" song that played changes back to headphones and the "new" symbol changes to the mute symbol.

How would you achieve something like that?

Upvotes: 0

Views: 338

Answers (1)

Stanislav Kvitash
Stanislav Kvitash

Reputation: 4622

I think you can use ngClass directive to dynamically toggle css classes using the state of the song which is currently playing. Do not know how exactly you code in controller looks like, but hope my idea will help you. So for the markup you can use something like (it is a good practice to use track by for repeaters and one time bindings if you care about performance):

<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>

And in the controller you can have the method that will toggle the state of the song that was clicked:

 $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
    //...

 }

Hope this will help you.

Upvotes: 2

Related Questions