How to insert audio file into SQL Server and retrieve it back and play it?

This is how the form looks like.

This is the source code,
This is the code for inserting audio file into sql server,
SqlConnection con = new SqlConnection(“Data Source=DEV-ARNOLD;Initial Catalog=Sample;User ID=sa;Password=passw0rd”);
SqlCommand com = new SqlCommand(“insert into tblVoice(FileName, FilePath, fldvoice) values(@Filename,@FilePath,@voice)”, con);
OpenFileDialog fileDialog = new OpenFileDialog();
fileDialog.ShowDialog();

byte[] stream = File.ReadAllBytes(fileDialog.FileName);
if (stream.Length > 0)
{
com.Parameters.AddWithValue(“@Filename”, fileDialog.SafeFileName);
com.Parameters.AddWithValue(“@FilePath”, fileDialog.FileName);
com.Parameters.AddWithValue(“@voice”, stream);
con.Open();
int result = com.ExecuteNonQuery();
if (result > 0)
MessageBox.Show(“insert done”);
con.Close();
}
This is the code for retrieving the audio file from sql server,
SqlConnection con = new SqlConnection(“Data Source=DEV-ARNOLD;Initial Catalog=Sample;User ID=sa;Password=passw0rd”);
SqlCommand com = new SqlCommand(“select * from tblVoice”, con);
con.Open();
DataTable dt = new DataTable();
SqlDataReader dr = com.ExecuteReader();
OpenFileDialog fileDialog = new OpenFileDialog();
fileDialog.ShowDialog();
dt.Load(dr);
dr.Close();
con.Close();
byte[] stream = null;
string path = @”C:\SynRISTempFiles\”;
string name = string.Empty;
foreach (DataRow rw in dt.Rows)
{
if (Convert.ToString(rw[0]) == fileDialog.SafeFileName)
{
stream = (byte[])rw[2];
name = (string)rw[0];
}
}
File.WriteAllBytes(path + name, stream);
axWindowsMediaPlayer1.URL = path + name;

References that I used:
http://www.codeproject.com/KB/database/AudioInSQLServer.aspx
http://coder000.com/store-retrieve-binary-data-blobs-audio-video-image-exe-etc-in-database-in-vb-net/
http://www.codeproject.com/KB/audio-video/Concatenation_Wave_Files.aspx

Advertisements
This entry was posted in C# 3.5. Bookmark the permalink.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s