FLYYE_CS的博客

偶的.NET开发历程
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

其大体思想就是实现在线音视频内容提供并动态生成播放列表,给大家在线观看(之前做这个的目的就是实现校园网内的资源共享...).

主要页面文件就只有两个:Default.aspx(动态文件列表),Play.aspx(播放或下载)

 项目源文件下载:https://files.cnblogs.com/flyye_cs/music.rar

运行界面如下:


由于写这个只是为了练习一下,所以加了很多注释,主要代码如下:

Default.aspx.cs

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Configuration;
using benSoft.web.WebControls.PopupBox;

namespace music
{
    
/// <summary>
    
/// _Default 的摘要说明。
    
/// </summary>

    public class _Default : System.Web.UI.Page
    
{
        
protected System.Web.UI.HtmlControls.HtmlForm Form1;
        
protected System.Web.UI.WebControls.Label allRow;
        
protected System.Web.UI.WebControls.Label allPage;
        
protected System.Web.UI.WebControls.Label nowPage;
        
protected System.Web.UI.WebControls.Label sort;
        
protected System.Web.UI.WebControls.TextBox txtSearch;
        
protected System.Web.UI.WebControls.Button btnSearch;
        
protected System.Web.UI.WebControls.Button btnAllFiles;
        
protected System.Web.UI.WebControls.DataGrid dgMusic;
        
        
protected PopupBox popBox;
    
        
private void Page_Load(object sender, System.EventArgs e)
        
{
            
// 在此处放置用户代码以初始化页面
            if(!IsPostBack)
            
{
                ViewState[
"SortOrder"]="加入日期 DESC"//默认排序字段
                ViewState["SearchKey"]="*"//默认搜索关键字为任意匹配
                dgMusic.PageSize=Int32.Parse(ConfigurationSettings.AppSettings["DisplayCount"]); //设置每页显示条数
                GetMedia("加入日期","DESC","*");
                nowPage.Text
="1";

                
//弹出信息框
                PopupMsg();
            }

        }
        

        
#region Web 窗体设计器生成的代码
        
override protected void OnInit(EventArgs e)
        
{
            
//
            
// CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
            
//
            InitializeComponent();
            
base.OnInit(e);
        }

        
        
/// <summary>
        
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
        
/// 此方法的内容。
        
/// </summary>

        private void InitializeComponent()
        
{    
            
this.btnSearch.Click += new System.EventHandler(this.btnSearch_Click);
            
this.btnAllFiles.Click += new System.EventHandler(this.btnAllFiles_Click);
            
this.dgMusic.PageIndexChanged += new System.Web.UI.WebControls.DataGridPageChangedEventHandler(this.dgMusic_PageIndexChanged);
            
this.dgMusic.SortCommand += new System.Web.UI.WebControls.DataGridSortCommandEventHandler(this.dgMusic_SortCommand);
            
this.Load += new System.EventHandler(this.Page_Load);

        }

        
#endregion
                        

        
private void PopupMsg()
        
{
            popBox.Focus 
= false;        
            popBox.Sound 
="sound/default.wav";
            
string strAbout=@"<b>基于文件模式的音视频点播系统<br><br><div align='center'>Powered By <a href='#' onclick="+"\"top.location='mailto:happy365d@163.com'\" title='联系我'>Flyye</a> 2005</div><div align='center'><br><a href='#' onclick="+"\"top.location='http://wpa.qq.com/msgrd?V=1&Uin=109317193&Site=flyye.3322.org&Menu=yes'\" title='有事请Q我'>QQ:109317193</a></div></b>";
            
if(ConfigurationSettings.AppSettings["MsgType"]=="1")
                popBox.Text 
= strAbout;
            
else
            
{
                
if(Request.QueryString["CopyRight"]!=null)
                    popBox.Text
=strAbout;
                
else
                    popBox.Text 
= ConfigurationSettings.AppSettings["MsgText"];
            }

            popBox.CreatePopup();
        }


        
private ArrayList GetFilesFromPaths(string searchFolder,string searchType,string searchValue)
        
{            
            ArrayList myReturn
=new ArrayList(); //返回文件集合            
            ArrayList myFolder=new ArrayList(); //多虚拟目录集合
            string[] strType; //多文件后缀集合
            string[] strTemp; //临时一维数组表            

            
if(searchFolder.IndexOf("|")!=-1//多目录
            {
                strTemp
=searchFolder.Split(new char[]{'|'});
                myFolder.AddRange(strTemp);
            }

            
else //单目录
            {
                myFolder.Add(searchFolder);
            }


            
if(searchType.IndexOf("|")!=-1//多文件类型
            {
                strTemp
=searchType.Split(new char[]{'|'});
                strType
=strTemp;                
            }

            
else //单文件类型
            {
                strType
=new string[]{searchType};
            }


            
for(int k=0;k<myFolder.Count;k++//遍历所有虚拟目录(动态增加)
            {
                
string folder=Server.MapPath(myFolder[k].ToString()); //定位某一虚拟目录到物理路径                
                strTemp=Directory.GetDirectories(folder); //获取指定虚拟目录中的所有一级子目录列表
                if(strTemp.Length>0//有子目录
                {
                    
foreach(string s in strTemp)
                        myFolder.Add(myFolder[k]
+s.Substring(s.LastIndexOf("\\")+1)+"/"); //添加到虚拟目录集合
                }

                strTemp
=Directory.GetFiles(folder); //获取某一虚拟目录下所有文件的物理路径

                
for(int i=0;i<strTemp.Length;i++//逐一判断每个文件名的类型
                {
                    
int iEnd=strTemp[i].LastIndexOf(".");
                    
foreach(string s in strType) //遍历文件名后缀是否满足要求?
                    {
                        
if(strTemp[i].Substring(iEnd+1).ToLower()==s) //后缀名存在,则查询特定名称(searchValue)的文件
                        {
                            
if(searchValue=="*"//所有文件
                                myReturn.Add(strTemp[i]+"|"+myFolder[k]); //把满足要求的完整物理路径添加到一维数组中->"文件物理路径|虚拟目录"
                            else //文件名匹配查询
                            {
                                
string temp=strTemp[i]; //要转换成小写的临时字符串,以便搜索英文名
                                if(temp.Substring(temp.LastIndexOf("\\")+1).ToLower().IndexOf(searchValue)!=-1//如果找到匹配文件名
                                    myReturn.Add(strTemp[i]+"|"+myFolder[k]); //添加记录
                            }

                            
break;
                        }

                    }

                }

            }
            
            
return myReturn; // 返回满足需求所有路径的集合
        }


        
private void GetMedia(string strName,string strValue,string strSearch)
        
{
            
//获取满足需求的所有文件路径集合
            IEnumerator myFile = GetFilesFromPaths(ConfigurationSettings.AppSettings["MediaFolder"],ConfigurationSettings.AppSettings["MediaType"],strSearch).GetEnumerator();

            DataTable dt
=new DataTable();            
            dt.Columns.Add(
new DataColumn("媒体名称"typeof(String)));
            dt.Columns.Add(
new DataColumn("媒体类型"typeof(String)));
            dt.Columns.Add(
new DataColumn("加入日期"typeof(DateTime)));
            dt.Columns.Add(
new DataColumn("在线播放"typeof(String)));
            dt.Columns.Add(
new DataColumn("下载保存"typeof(String)));

            
for(int i=0;i<dt.Columns.Count;i++)
            
{
                
if(dt.Columns[i].ColumnName==strName) //给排序字段加上图象提示
                {
                    
if(strValue=="ASC")
                    
{
                        strName
=dt.Columns[i].ColumnName+" <img border='0' src='images/up.gif'>";
                        dt.Columns[i].ColumnName
=strName;
                    }

                    
else
                    
{
                        
if(strValue=="DESC")
                        
{
                            strName
=dt.Columns[i].ColumnName+=" <img border='0' src='images/down.gif'>";
                            dt.Columns[i].ColumnName
=strName;
                        }

                    }

                    
break;
                }

            }
            

            DataRow dr;
            
while( myFile.MoveNext() ) //逐个读取文件集合中的每个路径
            {
                
string str=myFile.Current.ToString();
                
string[] dir=str.Split(new char[]{'|'});

                
int iStart=dir[0].LastIndexOf("\\");
                
int iEnd=dir[0].LastIndexOf(".");
                
if(iEnd!=-1)
                
{
                    dr
=dt.NewRow();                    
                    dr[
0]=dir[0].Substring(iStart+1,iEnd-iStart-1);    
                    dr[
1]=dir[0].Substring(iEnd).ToLower();
                    dr[
2]=Directory.GetLastWriteTime(dir[0]);
                    dr[
3]="<div align='center'><a title='在线播放:"+dr[0]+"' href=\"Play.aspx?MediaPath="+dir[1]+dr[0]+dr[1]+"&Operation=Play\"><img border='0' src='images/play.gif'></a></div>";
                    dr[
4]="<div align='center'><a title='下载:"+dr[0]+"' href=\"Play.aspx?MediaPath="+dir[1]+dr[0]+dr[1]+"&Operation=DownLoad\"><img border='0' src='images/download.gif'></a></div>";
                    
                    dr[
0]="<span title='"+dr[0]+"' class='flow1'>"+dr[0]+"</span>";
                    dr[
1]="<span class='flow2'>"+dr[1]+"</span>";

                    dr[
3]="<span class='flow2'>"+dr[3]+"</span>";
                    dr[
4]="<span class='flow2'>"+dr[4]+"</span>";

                    dt.Rows.Add(dr);
                }

            }

            
            DataView dv 
= new DataView(dt);
            dv.Sort
=strName+" "+strValue; //排序规则                        
            
            dgMusic.DataSource
=dv;
            dgMusic.DataBind();        
            
            allRow.Text
=dt.Rows.Count.ToString();
            allPage.Text
=dgMusic.PageCount.ToString();
            sort.Text
="<a title='点击各表头文字部分以重新排序'>已排序:"+strName+"</a>";
        }

        
        
private void dgMusic_SortCommand(object source, System.Web.UI.WebControls.DataGridSortCommandEventArgs e)
        
{
            dgMusic.CurrentPageIndex
=0;
            nowPage.Text
="1";

            
string strSort=e.SortExpression;
            
if(strSort.IndexOf("<")!=-1)
                strSort
=strSort.Substring(0,strSort.IndexOf("<")-1);
            
            
if(ViewState["SortOrder"].ToString().EndsWith("DESC"))
            
{
                ViewState[
"SortOrder"]=strSort+" ASC";
                GetMedia(strSort,
"ASC",ViewState["SearchKey"].ToString());
            }

            
else
            
{
                
if(ViewState["SortOrder"].ToString().EndsWith("ASC"))
                
{
                    ViewState[
"SortOrder"]=strSort+" DESC";
                    GetMedia(strSort,
"DESC",ViewState["SearchKey"].ToString());
                }

            }


        }


        
private void dgMusic_PageIndexChanged(object source, System.Web.UI.WebControls.DataGridPageChangedEventArgs e)
        
{
            dgMusic.CurrentPageIndex 
= e.NewPageIndex;
            nowPage.Text
=Convert.ToString(e.NewPageIndex+1);            
            
string[] str = ViewState["SortOrder"].ToString().Split(new char[]{' '});
            GetMedia(str[
0],str[1],ViewState["SearchKey"].ToString());
        }


        
private void btnSearch_Click(object sender, System.EventArgs e)
        
{
            dgMusic.CurrentPageIndex
=0;
            nowPage.Text
="1";
            
string[] str = ViewState["SortOrder"].ToString().Split(new char[]{' '});
            
            
if(txtSearch.Text.Trim()=="")
                ViewState[
"SearchKey"]="*";
            
else
                ViewState[
"SearchKey"]=txtSearch.Text.ToLower(); //转换成小写,以便搜索英文名

            GetMedia(str[
0],str[1],ViewState["SearchKey"].ToString());
        }


        
private void btnAllFiles_Click(object sender, System.EventArgs e)
        
{
            dgMusic.CurrentPageIndex
=0;
            nowPage.Text
="1";
            txtSearch.Text
="";
            
string[] str = ViewState["SortOrder"].ToString().Split(new char[]{' '});

            ViewState[
"SearchKey"]="*";

            GetMedia(str[
0],str[1],ViewState["SearchKey"].ToString());
        }
    
    }

}

Play.aspx.cs

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Text; //Coding
using System.Configuration;
using System.Collections.Specialized;
using System.IO;

namespace music
{
    
/// <summary>
    
/// Play 的摘要说明。
    
/// </summary>

    public class Play : System.Web.UI.Page
    
{
        
private void Page_Load(object sender, System.EventArgs e)
        
{
            
// 查询参数不能为空
            if(Request.QueryString["MediaPath"]!=null&&Request.QueryString["MediaPath"]!=string.Empty&&Request.QueryString["Operation"]!=null&&Request.QueryString["Operation"]!=string.Empty)
            
{
                
//判断文件是否存在,文件格式是否允许播放或提供下载
                DirectoryInfo file;
                
try
                
{
                    file
=new DirectoryInfo(Server.MapPath(Request.QueryString["MediaPath"])); //防止访问恶意文件路径使程序出错
                }

                
catch
                
{
                    Response.Write(
"<script>window.alert('非法文件操作!!!');history.back();</script>");
                    
return;
                }


                
if(System.IO.File.Exists(file.FullName)) //文件存在
                {
                    
string strType=file.FullName;                    
                    strType
=strType.Substring(strType.LastIndexOf(".")+1);
                    
string[] strTemp=ConfigurationSettings.AppSettings["MediaType"].Split(new char[]{'|'});

                    
int i;
                    
for(i=0;i<strTemp.Length;i++)
                    
{
                        
if(strType==strTemp[i])
                        
{
                            i
=-1// -1 表示满足文件后缀名要求
                            break;
                        }

                    }

                    
if(i!=-1//文件后缀名不合法
                    {
                        Response.Write(
"<script>window.alert('您所请求的文件类型不允许操作!');history.back();</script>");
                        
return;
                    }

                }

                
else //不存在
                {
                    Response.Write(
"<script>window.alert('您所请求的文件不存在!');history.back();</script>");
                    
return;
                }


                
switch(Request.QueryString["Operation"])
                
{
                    
case "Play"//在线播放,动态生成单播列表.m3u
                        System.Web.HttpContext.Current.Response.Clear();
                        System.Web.HttpContext.Current.Response.ContentType 
= "audio/mpegurl"//MIME中.m3u格式content-type为audio/mpegurl
                        string str="http://"+Request.ServerVariables["HTTP_HOST"]+Request.QueryString["MediaPath"];            
                        
byte[] content=Coding(str,936); //简体中文的代码页是 936
                        System.Web.HttpContext.Current.Response.OutputStream.Write(content,0,content.Length);
                        System.Web.HttpContext.Current.Response.End();
                        
break;
                    
case "DownLoad"//下载媒体
                        string str2=Request.QueryString["MediaPath"].Substring(Request.QueryString["MediaPath"].LastIndexOf("/")+1);
                        System.Web.HttpContext.Current.Response.Clear();
                        System.Web.HttpContext.Current.Response.AppendHeader(
"content-disposition""attachment; filename=\"" + System.Web.HttpUtility.UrlEncode(str2,System.Text.Encoding.UTF8) + "\"");
                        
try
                        
{
                            System.Web.HttpContext.Current.Response.WriteFile(file.FullName);
                        }

                        
catch
                        
{
                            Response.Write(
"对不起,该文件已被服务器占用,可能是服务器正在使用或下载它,请稍后再试!");
                        }

                        System.Web.HttpContext.Current.Response.End();
                        
break;
                    
default//操作不存在
                        Response.Write("<script>window.alert('您所请求的操作无效!');history.back();</script>");
                        
break;
                }
                
            }

            
else
                Response.Write(
"<script>window.alert('您所提交的参数无效!');history.back();</script>");            
        }


        
public byte[] Coding(string str, int codePage)
        
{
            Encoding targetEncoding;
            
byte[] encodedChars;

            
// Gets the encoding for the specified code page.
            targetEncoding = Encoding.GetEncoding(codePage);

            
// Gets the byte representation of the specified string.
            encodedChars = targetEncoding.GetBytes(str);

            
return encodedChars;            
        }


        
#region Web 窗体设计器生成的代码
        
override protected void OnInit(EventArgs e)
        
{
            
//
            
// CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
            
//
            InitializeComponent();
            
base.OnInit(e);
        }

        
        
/// <summary>
        
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
        
/// 此方法的内容。
        
/// </summary>

        private void InitializeComponent()
        
{    
            
this.Load += new System.EventHandler(this.Page_Load);
        }

        
#endregion

    }

}

如果在本机测试项目(music)的话,请按照web.config中的要求设置一下就OK了!