.

Tuesday, June 17, 2008

Play mp3 in browser from SQL Server

I am storing MP3's in an SQL database. Users would like to be able to go to a page and play files from in the browser instead of having to download them. Now downloading them works fine but when I try to have them play in the browser the WM player control appears on the web page but no file appears to be loaded. I am loading the file from a .ashx page.

Here is the code for my control on my aspx page:



http://www.microsoft.com/Windows/MediaPlayer/" name="mediaplayer1" width="320" height="240" loop="false"
src="media_handler।ashx?m=<%=Session["m"] %>&id=<%# Eval("id") %>"><'/ embed>








I have verified that the variables are appearing correctly by viewing the source. The source ends up something along the lines of "media_handler.ashx?m=1&id=20"

Here is the code from my .ashx page:

<%@ WebHandler Language="C#" Class="media_handler" %>

using System;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using Microsoft.Practices.EnterpriseLibrary.Data.Sql;

public class media_handler : IHttpHandler {

public void ProcessRequest (HttpContext context) {
try
{
int id = int.Parse(System.Web.HttpContext.Current.Request.QueryString["id"].ToString());
int mid = int.Parse(System.Web.HttpContext.Current.Request.QueryString["m"].ToString());

Media m = new Media();
SqlDataReader dr = m.View_DR(id);
DataTable dt = m.View(id);

while (dr.Read())
{
if (dt.Rows[0][9].ToString() != "2") // This is to evaluate if the file is a .pdf or .mp3. PDFs will be downloaded, MP3s will be played in the browser.
{
context.Response.AddHeader("content-disposition", "attachment;filename=" + dr["filename"].ToString());

}


context.Response.ContentType = dr["contenttype"].ToString(); context.Response.BinaryWrite((byte[])dr["data"]);
}
dr.Close();
/*}
else
{
throw new Exception();
}*/
}
catch (Exception)
{
//Response.Redirect("login.aspx");
}
}

public bool IsReusable {
get {
return false;
}
}

}



Does anyone have any thoughts?

No comments:

.