Hi guys,in this article you are presented with how to Store/retrieve audio files in SQL Server 2005.the main aspect of this article is how to store the audio data which is in binary format into SQL Server.The Process of Retrieving this Data again from Sql Server and playing it using Windows media player component object model tool is some how tricky!
As you know all of audio files and pictures in your computer are in Binary format.that mean internally they have 0's and 1's.So if you want to store these kind of files into SQL Server 2005,you should have a field in SQL Server 2005 which data type should be "varbinary(max)".
this data type is capable of storing binary files in it.note that you can store anything in this kind of data type,there is no restriction if you wish to store some text files in this field(varbinary), because every Data in computer at its last point is converted to 0 and 1 (binary).
You should be familiar with C# and Sql Server and File processing in .Net.if So then hop to next stage.
Using the Code
In my code i have used a database named "Sample".There is a table (tblVoice) in it which has a field (fldVoice)in binary format.I mean its data type is varbinary(max).This is all about the Sql Server 2005 i used in my project.
I created a win application project in c# language.in my form i have used two button one for inserting the audio file into SQL SErver 2005 and another for retrieving it from SQL sErver and playing that in Windows media player.There is also a windows media player in my form.i brought that from going to toolbox and right clicking and choosing an item in com tab.in this tab you should navigate to windows media player and afrer finding that clicking ok to attach this COM object to your toolbox.
Then you should drag and drop this windows media player into your form.and the rest of the work is done in Click event of the buttons.
In my project i have an audio file in my D:\ drive by the name of m.wma.
For inserting an audio file you should first convert that file into arrays of byte.in this way you can then store this byte array into fldVoice.
byte stream = File.ReadAllBytes(@"d:\m.wma");
For retrieving the audio file from the database you should simply cast the retrieved data into byte array:
SqlCommand com = new SqlCommand("select * from tblVoice", con);
DataTable dt = new DataTable();
SqlDataReader dr = com.ExecuteReader();
byte stream = (byte)dt.Rows;
Windows media player can read files.it cant read any stream.because of this drawback i first created a file with .wma extension and store my byte array in it and after that i give this file to URL of windows media player for playing my file:
axWindowsMediaPlayer1.URL = "D:\\news.wma";
Points of Interest
I came to this concludion that windows media player is just able to read a file no Stream.