通过angular js处理APlayer——动态播放音乐 [英] handle APlayer through angular js - play music dynamically

查看:13
本文介绍了通过angular js处理APlayer——动态播放音乐的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 angular js 的新手 - 尝试使用 Aplayer

构建音频播放

任务:-1.动态播放音乐2.点击相册获取json数据并添加到播放器

(function() {'使用严格';angular.module('app', []);有角的.module('应用').directive('玩家', 玩家);函数播放器(){返回 {限制:'交流',链接:函数(范围,元素,属性){//`element` 是指令附加到的角度元素//APlayer 需要原生的var nativeElement = element[0];var ap1 = 新 APlayer({元素:原生元素,狭隘:虚假,自动播放:真实,showlrc: 假,互斥量:真,主题:'#e6d0b2',预加载:'元数据',模式:'循环',音乐: {标题: attrs["playerTitle"],作者: attrs["playerAuthor"],url: attrs["playerUrl"],图片: attrs["playerPic"]}});ap1.on('播放', 函数() {console.log('播放');});ap1.on('播放', 函数() {console.log('play play');});ap1.on('暂停', function() {console.log('暂停');});ap1.on('canplay', function() {console.log('canplay');});ap1.on('播放', function() {console.log('播放');});ap1.on('结束', function() {console.log('结束');});ap1.on('错误', 函数() {console.log('错误');});}};}})();

<html lang="en" ng-app="app"><头><meta charset="utf-8"><script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.4/angular.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/aplayer/1.6.0/APlayer.min.js"></script><script src="script.js"></script><身体><div class="玩家"数据播放器标题=准备"data-player-author="汉斯·季默/理查德·哈维"data-player-url="http://devtest.qiniudn.com/Preparation.mp3"data-player-pic="http://devtest.qiniudn.com/Preparation.jpg"></div></html>

如何通过点击专辑将音乐文件动态传递给Aplayer.

解决方案

根据 Aplayer 源代码,无法动态替换音乐曲目或播放列表.API 只公开 setMusic 方法,允许在音乐播放列表中选择曲目索引.

要显示您的专辑,您需要先使用会调用您的 tracks API 的服务加载它们.

加载后,您可以将它们注入播放器指令并选择要播放的曲目的索引.

这是一个示例代码片段:

  • 一个 musicService 来处理您的音乐库

  • 一个 TrackController 来加载和显示您的音乐库

  • 修改后的 player 指令来处理曲目和当前曲目索引

<块引用>

注意:我正在使用 免费音乐档案 中的免费音乐来演示此演示.

(function() {'使用严格';angular.module('app', []);有角的.module('应用').factory('musicService', ['$timeout', musicService]).controller('TracksController', ['$scope', 'musicService', TracksController]).directive('玩家', 玩家);功能音乐服务($超时){返回 {加载轨道:函数(){//模拟一个 1500 毫秒的 $http api 调用返回 $timeout(function() {返回 [{标题:'在阳光下拖延',作者:'旋转线',网址:'https://freemusicarchive.org/music/download/e7fee95c2d7f7b1ea8d4260850a6128842eb85a4',图片:'https://freemusicarchive.org/file/images/artists/The_Spin_Wires_-_20170510154106040.jpg?width=290&height=290'},{title: 'осоле',作者:'科斯塔T',网址:'https://freemusicarchive.org/music/download/0e4d722be7bd7ca334970b5407b3e5654b95f7a2',图片:'https://freemusicarchive.org/file/images/tracks/Track_-_2017050264944176?method=crop&width=290&height=290'}];}, 1500);}}}功能轨道控制器($范围,音乐服务){$scope.loadingTracks = true;$scope.showPlayer = false;音乐服务.loadTracks().then(function(tracks) {//加载轨道后,更新范围$scope.tracks = 轨道;$scope.loadingTracks = false;});$scope.play = function(trackIndex) {$scope.trackIndex = trackIndex;$scope.showPlayer = true;}}函数播放器(){返回 {限制:'交流',范围: {曲目:'=',轨道索引:'='},链接:链接};功能链接(范围,元素,属性){var player = new APlayer({狭隘:真实,模式:订单",音乐:scope.tracks});//注意 trackIndex 的变化范围.$watch(功能(范围){//返回 watch 表达式的结果",因为它更有效//@see http://www.bennadel.com/blog/2852-understanding-how-to-use-scope-watch-with-controller-as-in-angularjs.htm返回范围.trackIndex;},功能(当前索引,以前的索引){//由于 currentIndex 是一个整数,if(0) 等于 if(false)//但是我们可以使用正则表达式来检查它是一个整数如果 (/\d/.test(currentIndex)) {player.setMusic(parseInt(currentIndex));播放器播放();}});}}})();

<html lang="en" ng-app="app"><头><meta charset="utf-8"><script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.4/angular.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/aplayer/1.6.0/APlayer.min.js"></script><风格>乌利{列表样式类型:无;}ul li * {垂直对齐:中间}</风格><body ng-controller="TracksController"><div ng-if="loadingTracks">正在加载曲目,请稍候...</div><ul><li ng-repeat="track in track"><img ng-src="{{track.pic}}" width="64" height="64"><button ng-click="play($index)">播放</button>{{track.author}}/{{track.title}}<div ng-if="tracks && showPlayer"><h2>正在播放</h2><div>{{tracks[trackIndex].author}}/{{tracks[trackIndex].title}}</div><div class="player" data-tracks="tracks" data-track-index="trackIndex"></div>

</html>

I am new to angular js - trying to build an audio play using Aplayer

Task:- 1. Play music dynamically 2. On click of album get json data and add to aplayer

(function() {
      'use strict';
    
      angular.module('app', []);
    
      angular
      .module('app')
      .directive('aplayer', aplayer);
    
      function aplayer() {
        return {
          restrict: 'AC',
          link: function(scope, element, attrs) {
            // `element` is the angular element the directive is attached to 
            // APlayer need the native one
            var nativeElement = element[0];
            var ap1 = new APlayer({
              element: nativeElement,
              narrow: false,
              autoplay: true,
              showlrc: false,
              mutex: true,
              theme: '#e6d0b2',
              preload: 'metadata',
              mode: 'circulation',
              music: {
                title: attrs["playerTitle"],
                author: attrs["playerAuthor"],
                url: attrs["playerUrl"],
                pic: attrs["playerPic"]
            }
        });
            ap1.on('play', function() {
              console.log('play');
          });
            ap1.on('play', function() {
              console.log('play play');
          });
            ap1.on('pause', function() {
              console.log('pause');
          });
            ap1.on('canplay', function() {
              console.log('canplay');
          });
            ap1.on('playing', function() {
              console.log('playing');
          });
            ap1.on('ended', function() {
              console.log('ended');
          });
            ap1.on('error', function() {
              console.log('error');
          });
    
        }
    };
    }
    
    })();

<!doctype html>

<html lang="en" ng-app="app">

<head>
  <meta charset="utf-8">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.4/angular.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/aplayer/1.6.0/APlayer.min.js"></script>
  <script src="script.js"></script>
</head>

<body>
  <div class="aplayer" 
       data-player-title="Preparation" 
       data-player-author="Hans Zimmer/Richard Harvey" 
       data-player-url="http://devtest.qiniudn.com/Preparation.mp3"
       data-player-pic="http://devtest.qiniudn.com/Preparation.jpg"></div>
</body>

</html>

How to pass music files dynamically to Aplayer on click of an album.

解决方案

According to Aplayer source code, it's not possible to replace music track or playlist dynamically. API only expose setMusic method which allow to choose track index in music playlist.

To display your albums, you need to load them first using a service which will call your tracks API.

Once loaded, you can inject them to your aplayer directive and choose the index of the track to play.

Here is a sample snippet with :

  • a musicService to handle your music library

  • a TrackController to load and display your music library

  • a modified aplayer directive to handle tracks and current track index

Note: I'm using free music from Free Music Archive for this demo.

(function() {
  'use strict';

  angular.module('app', []);

  angular
    .module('app')
    .factory('musicService', ['$timeout', musicService])
    .controller('TracksController', ['$scope', 'musicService', TracksController])
    .directive('aplayer', aplayer);


  function musicService($timeout) {
    return {
      loadTracks: function() {
        // Simulate a 1500 ms $http api call
        return $timeout(function() {
          return [{
              title: 'Procrastinating in the Sun',
              author: 'The Spin Wires',
              url: 'https://freemusicarchive.org/music/download/e7fee95c2d7f7b1ea8d4260850a6128842eb85a4',
              pic: 'https://freemusicarchive.org/file/images/artists/The_Spin_Wires_-_20170510154106040.jpg?width=290&height=290'
            },
            {
              title: 'осоле',
              author: 'Kosta T',
              url: 'https://freemusicarchive.org/music/download/0e4d722be7bd7ca334970b5407b3e5654b95f7a2',
              pic: 'https://freemusicarchive.org/file/images/tracks/Track_-_2017050264944176?method=crop&width=290&height=290'
            }
          ];
        }, 1500);


      }
    }
  }

  function TracksController($scope, musicService) {

    $scope.loadingTracks = true;
    $scope.showPlayer = false;

    musicService.loadTracks()
      .then(function(tracks) {
        // Once tracks are loaded, update scope
        $scope.tracks = tracks;
        $scope.loadingTracks = false;
      });

    $scope.play = function(trackIndex) {
      $scope.trackIndex = trackIndex;
      $scope.showPlayer = true;
    }
  }


  function aplayer() {
    return {
      restrict: 'AC',
      scope: {
        tracks: '=',
        trackIndex: '='
      },
      link: link
    };

    function link(scope, element, attrs) {

      var player = new APlayer({
        narrow: true,
        mode: "order",
        music: scope.tracks
      });

      // Watch for trackIndex changes
      scope.$watch(
        function(scope) {
          // Return the "result" of the watch expression as it's more efficient
          // @see http://www.bennadel.com/blog/2852-understanding-how-to-use-scope-watch-with-controller-as-in-angularjs.htm
          return scope.trackIndex;
        },
        function(currentIndex, previousIndex) {
          // As currentIndex is an integer, if(0) equals if(false)
          // But we can use a regular expression to check it's an integer
          if (/\d/.test(currentIndex)) {
            player.setMusic(parseInt(currentIndex));
            player.play();
          }
        });

    }
  }

})();

<!doctype html>

<html lang="en" ng-app="app">

<head>
  <meta charset="utf-8">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.4/angular.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/aplayer/1.6.0/APlayer.min.js"></script>
  <style>
    ul li {
      list-style-type: none;
    }
    
    ul li * {
      vertical-align: middle
    }
  </style>
</head>

<body ng-controller="TracksController">

  <div ng-if="loadingTracks">Loading tracks, please wait...</div>
  <ul>
    <li ng-repeat="track in tracks">
      <img ng-src="{{track.pic}}" width="64" height="64">
      <button ng-click="play($index)">Play</button> {{track.author}} / {{track.title}}
    </li>
  </ul>

  <div ng-if="tracks && showPlayer">
    <h2>Now playing</h2>
    <div>{{tracks[trackIndex].author}} / {{tracks[trackIndex].title}}</div>

    <div class="aplayer" data-tracks="tracks" data-track-index="trackIndex"></div>
  </div>

</body>

</html>

这篇关于通过angular js处理APlayer——动态播放音乐的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆