`

音乐播放((jsp+servlet+html+js))

阅读更多
 
                           在线音乐播放(jsp+servlet+html+js)
在页面选择歌曲文件夹(可以包含子目录),提交后后台生成播放列表。
当音乐文件过多时,页面会有相应的提示信息。
单击播放列表中的因为,可播放选择的音乐文件。

文件描述:
FileNameFilter.java:文件过滤器,仅扫描mp3,.wav,.mid,.rm,.rmvb,.flv,.swf,.wmv类型文件。
PlayListServlet.java:根据选择的目录,生成对应的播放列表。
PlayServlet.java:单击一首歌曲时,生成播放器并自动开始播放。
folderSelectTree.js:生成文件夹树形结构。
jsCoverCtrl.js:进行页面提示。
playIndex.jsp:选择歌曲目录的页面。

具体实现:
FileNameFilter.java:
import java.io.File;
import java.io.FileFilter;

/**
 * 文件:FileNameFilter.java
 * 描述:TODO
 * 作者:EX-QINCIDONG001
 * 日期:2012-2-15
 */

/**
 * @author EX-QINCIDONG001
 * 文件扩展名过滤器。
 */
public class FileNameFilter implements FileFilter{
 // 可接收的文件类型,.mp3,.wav,.mid,.rm,.rmvb,.flv,.swf,.wmv
 private String[] accepts;
 
 public FileNameFilter(String[] accepts) {
  this.accepts = accepts;
 }
 /* (non-Javadoc)
  * @see java.io.FileFilter#accept(java.io.File)
  */
 @Override
 public boolean accept(File pathname) {
  boolean ok = false;
  if (pathname.isFile()) {
   for(String ext : accepts) {
    if (pathname.getName().endsWith(ext)) {
     ok = true;
     break;
    }
   }   
  }
  else {
   ok = true;
  }
  return ok;
 }

}

PlayListServlet.java:
import java.io.File;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 文件:PlayListServlet.java
 * 描述:TODO
 * 作者:luckystar2008
 * 日期:2012-2-14
 */

/**
 * @author luckystar2008
 *  生成播放列表。
 */
public class PlayListServlet extends HttpServlet {
 int index = 0;
 String playlist = "";
 String tr = "<tr>";
 String accepts[] = { ".mp3", ".wma", ".mid", ".rm", ".rmvb", ".flv", ".swf" };
 /**
  * serialVersionUID
  */
 private static final long serialVersionUID = 6523452712664052932L;

 @Override
 protected void doGet(HttpServletRequest req, HttpServletResponse resp)
   throws ServletException, IOException {
  // TODO Auto-generated method stub
  super.doGet(req, resp);
 }

 @Override
 protected void doPost(HttpServletRequest req, HttpServletResponse resp)
   throws ServletException, IOException {
  req.setCharacterEncoding("gb18030");

  String dir = req.getParameter("musicDir");
  dir = dir.replace("\\", "/");
  String musicList = makePlayList(dir);
  resp.setContentType("text/html;charset=gb18030");
  resp.setCharacterEncoding("gb18030");

  String tip = "<script type='text/javascript' src='jsCoverCtrl.js'></script>\n";
  tip += "<script type='text/javascript' language='JavaScript'>\n";
  tip += "<!--\n";
  tip += "var currentPageStatus = document.readyState.toLowerCase();\n";
  tip += "JSCoverCtrl.viewWithString('正在加载页面.....请稍侯');\n";
  tip += "//-->\n";
  tip += "</script>\n";
  resp.getWriter().println(tip);
  resp.getWriter().println(musicList);

  String js = "<script>\n";
  js += "function tdMouseOver(o) {\n";
  js += " var tr = o;\n";
  js += "tr.style.cursor = 'hand';\n";
  js += "tr.style.backgroundColor = '#3366FF';\n";
  js += "}\n";

  js += "function tdMouseOut(o) {\n";
  js += "var tr = o;\n";
  js += "tr.style.backgroundColor = '#FFFFFF';\n";
  js += "}\n";

  js += "function flayMusic(o) {\n";
  js += "var tr = o;\n";

  js += "}\n";

  js += "function play(f){\n";
  // js += "alert(f);\n";
  js += "playForm.action = 'play.do';\n";
  js += "playForm.music.value = f;\n";
  js += "playForm.submit();\n";
  js += "}\n";

  js += "</script>;\n";

  String loading = "<script type='text/javascript' language='JavaScript'>\n";
  loading += " setInterval('doit()',100);\n";
  loading += " function doit(){\n";
  loading += " var currentPageStatus = document.readyState.toLowerCase();\n";
  loading += " if(currentPageStatus=='complete'){\n";
  loading += " JSCoverCtrl.hideAllCover();\n";
  loading += " }\n";
  loading += " }\n";
  loading += " </script>\n";

  resp.getWriter().println(loading);
  resp.getWriter().println(js);
  resp.getWriter().flush();
 }

 /**
  * 生成播放列表
  * 
  * @param dir
  *            : 歌曲所在目录。
  * @return
  */
 private synchronized String makePlayList(String dir) {
  String table = "<div><table border=1 style='font-size:13px;'>\n";
  makePlayList2(dir);
  table += playlist;
  table += "</table></div>\n";
  table += "<div style='float:left;'><iframe id='musicFrm' name='musicFrm' width='500px' height='220px'>\n</iframe></div>\n";
  table += "<form action='' method='post' name='playForm' target='musicFrm'><input type='hidden' name='music' ></form>\n";

  // HttpServlet是单实例的,所以要重置变量。。。
  playlist = "";
  index = 0;
  tr = "<tr>";
  return table;
 }

 /**
  * 生成tr,td
  * 
  * @param dir
  * @return
  */
 private synchronized void makePlayList2(String dir) {
  System.out.println(dir);
  if (dir == null || dir.trim().length() == 0) {
   return;
  } else {
   File dirs = new File(dir);
   if (dirs.exists()) {
    if (dirs.isDirectory()) {
     File[] files = dirs.listFiles(new FileNameFilter(accepts));
     for (File f : files) {
      if (f.isFile()) {
       index++;
       tr += "<td onmouseover='tdMouseOver(this);'onmouseout='tdMouseOut(this);' onclick=\"play('"
         + f.getAbsolutePath().replace("\\", "/")
         + "')\">"
         + (index < 10 ? "0" + index : index)
         + "."
         + f.getName() + "</td>" + "\n";
       System.out.println("index-->" + index);
      } else {
       makePlayList2(f.getAbsolutePath()
         .replace("\\", "/"));
      }

      if (index % 4 == 0) { // 1行4首歌曲
       tr += "</tr>";
       playlist += tr;
       tr = "<tr>";
      }
     }
    }
   }
  }
 }
}


PlayServlet.java:

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class PlayServlet
 */
public class PlayServlet extends HttpServlet {
 private static final long serialVersionUID = 1L;

 /**
  * @see HttpServlet#HttpServlet()
  */
 public PlayServlet() {
  super();
  // TODO Auto-generated constructor stub
 }

 /**
  * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
  *      response)
  */
 protected void doGet(HttpServletRequest request,
   HttpServletResponse response) throws ServletException, IOException {
  // TODO Auto-generated method stub
 }

 /**
  * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
  *      response)
  */
 protected void doPost(HttpServletRequest request,
   HttpServletResponse response) throws ServletException, IOException {
  request.setCharacterEncoding("gb18030");
  String musicPath = request.getParameter("music");
  String obj = "<object classid='clsid:22D6F312-B0F6-11D0-94AB-0080C74C7E95' id='MediaPlayer1' width='400' height='150'>";
  obj += " <param name='AudioStream' value='-1'>";
  obj += "<param name='AutoSize' value='0'>";
  obj += "<param name='AutoStart' value='-1'>";
  obj += "<param name='AnimationAtStart' value='-1'>";
  obj += "<param name='AllowScan' value='-1'>";
  obj += "<param name='AllowChangeDisplaySize' value='-1'>";
  obj += "<param name='AutoRewind' value='0'>";
  obj += "<param name='Balance' value='0'>";
  obj += "<param name='BaseURL' value>";
  obj += "<param name='BufferingTime' value='5'>";
  obj += "<param name='CaptioningID' value>";
  obj += "<param name='ClickToPlay' value='-1'>";
  obj += "<param name='CursorType' value='0'>";
  obj += "<param name='CurrentPosition' value='-1'>";
  obj += "<param name='CurrentMarker' value='0'>";
  obj += "<param name='DefaultFrame' value>";
  obj += "<param name='DisplayBackColor' value='0'>";
  obj += "<param name='DisplayForeColor' value='16777215'>";
  obj += "<param name='DisplayMode' value='0'>";
  obj += "<param name='DisplaySize' value='2'>";
  obj += "<param name='Enabled' value='-1'>";
  obj += "<param name='EnableContextMenu' value='-1'>";
  obj += "<param name='EnablePositionControls' value='-1'>";
  obj += "<param name='EnableFullScreenControls' value='0'>";
  obj += "<param name='EnableTracker' value='-1'>   ";
  obj += "<param name='Filename' value='" + musicPath + "'>";
  obj += "<param name='InvokeURLs' value='-1'>";
  obj += "<param name='Language' value='-1'>";
  obj += "<param name='Mute' value='0'>";
  obj += "<param name='PlayCount' value='1'>";
  obj += "<param name='PreviewMode' value='0'>";
  obj += "<param name='Rate' value='1'>";
  obj += "<param name='SAMILang' value>";
  obj += "<param name='SAMIStyle' value>";
  obj += "<param name='SAMIFileName' value>";
  obj += "<param name='SelectionStart' value='-1'>";
  obj += "<param name='SelectionEnd' value='-1'>";
  obj += "<param name='SendOpenStateChangeEvents' value='-1'>";
  obj += "<param name='SendWarningEvents' value='-1'>";
  obj += "<param name='SendErrorEvents' value='-1'>";
  obj += "<param name='SendKeyboardEvents' value='0'>";
  obj += "<param name='SendMouseClickEvents' value='0'>";
  obj += "<param name='SendMouseMoveEvents' value='0'>";
  obj += "<param name='SendPlayStateChangeEvents' value='-1'>";
  obj += "<param name='ShowCaptioning' value='0'>";
  obj += "<param name='ShowControls' value='-1'>";
  obj += "<param name='ShowAudioControls' value='-1'>";
  obj += "<param name='ShowDisplay' value='0'>";
  obj += "<param name='ShowGotoBar' value='0'>";
  obj += "<param name='ShowPositionControls' value='-1'>";
  obj += "<param name='ShowStatusBar' value='-1'>";
  obj += "<param name='ShowTracker' value='-1'>";
  obj += "<param name='TransparentAtStart' value='0'>";
  obj += "<param name='VideoBorderWidth' value='0'>";
  obj += "<param name='VideoBorderColor' value='0'>";
  obj += "<param name='VideoBorder3D' value='0'>";
  obj += "<param name='Volume' value='-40'>";
  obj += "<param name='WindowlessVideo' value='0'>";
  obj += "</object>";
  response.setContentType("text/html;charset=gb18030");
  response.getWriter().println(obj);
 }

}


folderSelectTree.js:
var FolderTree = function() {
 //var ft = this;
 // 文件夹图标,分别在树展开和关闭时显示
 this.driveImage = new Array("+", "-");
 // 要呈现树的容器ID
 this.containerId = '';
 // 初始化是否ok
 this.show = true;
   this.init = function(treeIcon, containerId) {
    if (treeIcon != null && !typeof (treeIcon) == Array) {
     alert("文件夹树形图标是一个数组,包含树展开和关闭,请确认!");
     this.show = false;
    }
    if (treeIcon != null) {
     this.driveImage = treeIcon;
    }
    if (containerId != null) {
     this.containerId = containerId;
    }
    this.makeFolderTree();
   },
   // 在指定的容器展现树
   this.makeFolderTree = function() {
    if (this.show) {
     var fso, s, n, e, x;
     var ul = "<ul id='drivelist'>";
     fso = new ActiveXObject("Scripting.FileSystemObject");
     e = new Enumerator(fso.Drives);

     for (; !e.atEnd(); e.moveNext()) {
      ul += "<li style='list-style:none;'><span  onclick='ft.liMouseClick(this);'>"
        + this.driveImage[0]
        + "</span><span>"
        + e.item()
        + "</span><input type=checkbox name='dir' value='"
        + e.item()
        + "' onclick='ft.checkConfirmOneSelected();'></li>";
     }

     ul += "</ul>";
     if (this.containerId == '') {
      document.body.innerHTML = ul;
     } else {
      document.getElementById(this.containerId).innerHTML = ul;
     }
    }
   },
   // 单击节点时,获取子目录并展现
   this.liMouseClick = function(o) {
    o = o.parentElement;
    var s1 = o.childNodes[0].innerHTML.toLowerCase();
    s1 = o.childNodes[0].childNodes[0].src;
    // 获取文件名
    s1 = s1.substring(s1.lastIndexOf('/')+1,s1.length);
    //s1 = s1.substring(s1.indexOf('src') , s1.length - 2);
    var s2 = this.driveImage[0];

    if (s2.indexOf(s1) > 0) {
     // 先判断是否已经单击过,未单击过才列出它的子目录。 
     if (o.childNodes.length <= 3) // 1个span(+,-),1个span(目录),1个checkbox
     {
      // 获取子目录和文件
      // 根目录
      var rootFolder = o.childNodes[1].innerText + "\\";
      var fso = new ActiveXObject(
        "Scripting.FileSystemObject");
      var folder = fso.GetFolder(rootFolder);

      var ul = "<ul>";
      // 列出子目录
      fc = new Enumerator(folder.SubFolders);
      for (; !fc.atEnd(); fc.moveNext()) {
       var li = "<li style='list-style:none;'><span  onclick='ft.liMouseClick(this);'>"
         + this.driveImage[0]
         + "</span><span>"
         + fc.item()
         + "</span><input type=checkbox name='dir' value='"
         + fc.item()
         + "' onclick='ft.checkConfirmOneSelected();'></li>";
       ul += li;
      }

      //fc = new Enumerator(folder.files);
      // 列出目录下的文件
      // for (; !fc.atEnd(); fc.moveNext())
      // {
      // var li = "<li style='list-style:none;'
      // onclick='liMouseClick(this);'><span>"+driveImage[0]+"</span><span>"+fc.item()+"</span></li>";
      // ul += li;
      // }

      ul += "</ul>";
      o.innerHTML = o.innerHTML + ul;
     }

     o.childNodes[0].innerHTML = this.driveImage[1];

    } else {
     for ( var i = 3; i < o.childNodes.length; i++) {
      o.removeChild(o.childNodes[i]);
     }
     o.childNodes[0].innerHTML = this.driveImage[0];
    }
   },
   // 保证只能选择一个目录
   this.checkConfirmOneSelected = function() {
    var checkboxs = document.getElementsByTagName('input');
    var index = 0;

    for ( var i = 0; i < checkboxs.length; i++) {
     if (checkboxs[i].type == 'checkbox') {
      if (checkboxs[i].checked) {
       index++;
      }
     }
    }

    if (index > 1) {
     alert('请选择一个文件夹!');
     return;
    }
   },
   // 返回选择的目录
   this.showSelectedFolder = function() {
    this.checkConfirmOneSelected();
    var checkboxs = document.getElementsByTagName('input');
    var selectedFolderString = '';

    for ( var i = 0; i < checkboxs.length; i++) {
     if (checkboxs[i].type == 'checkbox') {
      if (checkboxs[i].checked) {
       selectedFolderString = checkboxs[i].parentElement.childNodes[1].innerText + "/";
       break;
      }
     }
    }

    /*if (selectedFolderString != '')
    {
     alert('选择的文件夹是:' + selectedFolderString);
    }
    else {
     alert('未选择文件夹');
    }*/

    return (selectedFolderString);
   }
}

jsCoverCtrl.js:
var JSCoverCtrl = {
 createCover    :function(){
                  document.write("<div id='JSCoverCtrlLoadinglookup' style='position:absolute; top:20; left:20; z-index:10; visibility:hidden'><TABLE BORDER=0 CELLSPACING=0 CELLPADDING=0><TR><TD bgcolor=6487DC><TABLE  id='loadingTable' WIDTH=180 height=70 BORDER=0 CELLSPACING=2 CELLPADDING=0><TR><td bgcolor=E9F2FC align=center><font size=-1>正在查找数据, 请稍候...</font></td></tr></table></td></tr></table></div>");
                  document.write("<div id='JSCoverCtrlLoadingTemplate' style='position:absolute; top:20; left:20; z-index:10; visibility:hidden'><TABLE  BORDER=0 CELLSPACING=0 CELLPADDING=0><TR><TD bgcolor=6487DC><TABLE WIDTH=180 height=70 BORDER=0 CELLSPACING=2 CELLPADDING=0><TR><td bgcolor=E9F2FC align=center><font size=-1><span id=JSCoverCtrlLoadingText contenteditable=true>正在查找数据, 请稍候...</span></font></td></tr></table></td></tr></table></div>");
                  document.write("<div id='JSCoverCtrlCover' style='position:absolute; top:0; left:0; z-index:11; visibility:hidden; height:100%; width:100%' ><TABLE id='JSCoverCtrlCovertable' WIDTH=100% height=100% BORDER=0 CELLSPACING=0 CELLPADDING=0 ><TR ><TD align=center></td></tr></table></div>");
                 },
 //显示您所需要的提示---displapString
 viewWithString      :function(displayString){
                  if(displayString != null)
                  {
                    JSCoverCtrlLoadingText.innerHTML=displayString;
                    JSCoverCtrlLoadingTemplate.style.top=document.all("JSCoverCtrlCovertable").offsetHeight/2-35;
                    JSCoverCtrlLoadingTemplate.style.left=document.all("JSCoverCtrlCovertable").offsetWidth/2-70;
                    JSCoverCtrlLoadingTemplate.style.visibility="visible";
                  }
                  else {
                    JSCoverCtrlLoadinglookup.style.top=document.all("JSCoverCtrlCover").offsetHeight/2-20;
                    JSCoverCtrlLoadinglookup.style.left=document.all("JSCoverCtrlCover").offsetWidth/2-20;
                    JSCoverCtrlLoadinglookup.style.visibility="visible";
                  }
                  JSCoverCtrlCover.style.visibility="visible";
                 },
 //显示您所需要的提示---displapString
 hideAllCover      :function(){
                  if (JSCoverCtrlCover.style.visibility=="visible") JSCoverCtrlCover.style.visibility="hidden";
                  if (JSCoverCtrlLoadingTemplate.style.visibility=="visible") JSCoverCtrlLoadingTemplate.style.visibility="hidden";
                  if (JSCoverCtrlLoadinglookup.style.visibility=="visible") JSCoverCtrlLoadinglookup.style.visibility="hidden";
                }

}
JSCoverCtrl.createCover();


playIndex.jsp:
<%@ page language="java" contentType="text/html; charset=GB18030"
 pageEncoding="GB18030"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<meta http-equiv="cache-control" content="no-cache">
<title>Insert title here</title>
<script type="text/javascript" src="jsCoverCtrl.js"></script>
<script type="text/javascript" src="folderSelectTree.js"></script>

<script type="text/javascript">
 var ft;
 function submitForm() {
  var musicDir = playListForm.musicDir;
  var dir = ft.showSelectedFolder();
  if (dir == '') {
   alert('请选择一个文件夹!');
   return;
  }
  musicDir.value = dir;
  JSCoverCtrl.viewWithString('正在检查并提交.....请稍侯');
  playListForm.submit();
 }

 window.onload = function() {
   ft = new FolderTree();
  var treeIcons = new Array("<img src='./icons/folder.gif' width='15px' height='15px'>","<img src='./icons/folder-open.gif' width='15px' height='15px'>");
  ft.init(treeIcons,'tree');
 }
</script>
</head>
<body>
<form action="playlist.do" " method="post" name='playListForm'>
<table>
 <tr>
  <td>选择歌曲目录:</td>
  <td>
   <input type='hidden' name='musicDir' id="musicDir">
   <div id='tree'></div>
  </td>
 </tr>
 <tr align="center">
  <td><input type='button' value='确定' onclick='submitForm();'></td>
 </tr>
</table>
</form>

</body>
</html>
                           

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics