AngularJS小案例_簡易音樂播放器



<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>循環播放音樂</title>
    <script type="text/javascript" src="js/angular.min.js"></script>
    <script type="text/javascript">
    var app = angular.module("app",[]);
app.controller("AppController",["$scope",function($scope){

//音樂列表
var musicList = [

{addr:"music/two_tigers.mp3",geci:"兩隻老虎兩隻老虎 跑得快跑得快一隻沒有耳朵 一隻沒有尾巴真奇怪 真奇怪 "},
{addr:"music/worms_fly.mp3",geci:"黑黑的天空低垂 亮亮的繁星相隨 蟲兒飛蟲兒飛 你在思念誰 天上的星星流淚 地上的玫瑰枯萎 冷風吹冷風吹 只要有你陪 蟲兒飛花兒睡 一雙又一對才美 不怕天黑只怕心碎 不管累不累 也不管東南西北"},
{addr:"music/spring.mp3",geci:"春天在哪裏呀?  春天在哪裏呀?  春天在那青翠的山林裏  這裏有紅花呀,這裏有綠草  還有那會唱歌的小黃鸝  嘀哩哩嘀哩嘀哩哩,  嘀哩哩嘀哩嘀哩哩  春天在青翠的山林裏,  還有那會唱歌的小黃鸝"},
];

var index = 0;//當前音樂對象對應的下標

//播放狀態
$scope.isPlay = false;

var audioEle = null;
//當前正在播放的音樂對象
$scope.currentMusic = musicList[index];


//播放音樂
$scope.bofang = function(){
if(audioEle == null){
//創建audio元素  audio有play和pause的方法
audioEle = document.createElement("audio");
//指定歌曲路徑
audioEle.src = $scope.currentMusic.addr;

//綁定結束事件,實現自動播放
audioEle.onended = function(){
//手動更新視圖(解決音樂換掉是歌詞不換的問題)
$scope.$apply(function(){
//播放下一首
$scope.next();
});  };
  }

//調用播放方法
audioEle.play();
//更新播放狀態
$scope.isPlay = true;
};

//暫停播放
$scope.stop = function(){
audioEle.pause();//調用audio的暫停方法
$scope.isPlay = false;
};

//下一首
$scope.next = function(){
//判斷下標
if(index == musicList.length-1){
//alert("別點了,後邊沒有了");
index = 0;
}else{
index++;
}
//停掉正在播放的音樂
$scope.stop();
//重置當前音樂
$scope.currentMusic = musicList[index];
//將之前音樂元素置爲null
audioEle = null;

$scope.bofang();

};

//上一首
$scope.previous = function(){
//判斷下標
if(index == 0){
index = musicList.length-1;
}else{
//下標+1
index--;
}
//停掉正在播放的音樂
$scope.stop();

//重置當前音樂
$scope.currentMusic = musicList[index];
//將之前音樂元素置爲null
audioEle = null;

$scope.bofang();


};



}]);
    
    </script>
    <style type="text/css">
    .myplayer{
    width:300px;
    background-color: brown;
    }
    </style>
  </head>
  
  <body ng-app="app">
   <div ng-controller="AppController">
   
      <h3>簡易音樂播放器</h3>
 
  <div class="myplayer">
  <!--跑馬燈用來顯示歌詞 -->
  <marquee behivor="scroll" direction="left" ng-bind="currentMusic.geci">
  </marquee>
 
  <div class="myBtn">
  <button ng-click="previous()" >&lt;&lt;</button>
  <button ng-show="isPlay" ng-click="stop()">||</button>
  <button ng-hide="isPlay" ng-click="bofang()">▷</button>
  <button ng-click="next()">&gt;&gt;</button>
  </div>
  </div>
   </div>
  </body>
</html>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章