Tuesday, May 31, 2011

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("ConnectionString");
            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("ConnectionString");
            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/audio-video/Concatenation_Wave_Files.aspx

No comments:

Post a Comment