I have uploaded audio files (saved them) into the SQL Server 2005 database.

I need to prepare a "play sound" button to allow users to click it and listen to the sound.

I have the following code to retrieve the audio file from the database.

  protected void playsound_btn_Click(object sender, ImageClickEventArgs e)
  {
    Label Sound_nameLabel = (Label)QuestionsFormView.FindControl("Sound_nameLabel");
    string soundName = Sound_nameLabel.Text;

    SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["preschoolkidsConnectionString"].ConnectionString);
    connection.Open();

    SqlCommand dCmd = new SqlCommand("SelectAudioBySoundName", connection);
    dCmd.CommandType = CommandType.StoredProcedure;

    try
    {
      SqlParameter param = new SqlParameter("@Sound_name", SqlDbType.VarChar, 50);
      param.Value = soundName;
      dCmd.Parameters.Add(param);
      DataTable dt = new DataTable();
      SqlDataReader dr = dCmd.ExecuteReader();
      dt.Load(dr);

      byte[] stream = (byte[])dt.Rows[0][0];
    }

    catch
    {
      throw;
    }

    finally
    {
      dCmd.Dispose();
      connection.Close();
      connection.Dispose();
    }
  }

But I could not find a way to to code it so that can play it on user click.

Please help me...thank you.

p/s: im doing web application.

Dani AI

Generated

— you already have the audio bytes pulled from SQL, which is the hard part. The missing piece is exposing those bytes as an HTTP endpoint the browser can request, then pointing an HTML5 audio element at that endpoint. 's idea of injecting a player via JavaScript works, but using a small server-side stream endpoint plus the <audio> tag is simpler, more compatible and easier to debug.

Create a lightweight HTTP handler or controller action (for example PlaySound.ashx?name=...) that:

  • validates the incoming id/name,
  • queries the BLOB column,
  • sets the correct MIME type (e.g. audio/mpeg for mp3, audio/wav for wav),
  • streams the bytes to Response.OutputStream using SqlDataReader with CommandBehavior.SequentialAccess so you do not load the whole file into memory.

Example streaming pattern (C# handler):

public void ProcessRequest(HttpContext ctx)
{
    string name = ctx.Request.QueryString["name"];
    ctx.Response.Clear();
    using (var cn = new SqlConnection(...))
    using (var cmd = new SqlCommand("SelectAudioBySoundName", cn))
    {
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.AddWithValue("@Sound_name", name);
        cn.Open();
        using (var rdr = cmd.ExecuteReader(CommandBehavior.SingleRow | CommandBehavior.SequentialAccess))
        {
            if (rdr.Read())
            {
                long total = rdr.GetBytes(0, 0, null, 0, 0);
                ctx.Response.ContentType = "audio/mpeg";
                ctx.Response.AddHeader("Content-Length", total.ToString());
                int bufferSize = 8192;
                byte[] buffer = new byte[bufferSize];
                long pos = 0;
                int read;
                while ((read = (int)rdr.GetBytes(0, pos, buffer, 0, bufferSize)) > 0)
                {
                    ctx.Response.OutputStream.Write(buffer, 0, read);
                    pos += read;
                }
            }
        }
    }
    ctx.ApplicationInstance.CompleteRequest();
}

Then in the page use:

<audio controls src="/PlaySound.ashx?name=yourSoundName"></audio>

Quick tips: test the handler URL directly in the browser first; confirm Content-Type and bytes look correct; store MIME type or extension in the DB; validate input and secure the endpoint; for large files consider file storage/CDN instead of DB, and implement Range handling if users must seek.

Javascript is easier for this i think.


<script language="javascript" type="text/javascript">
function playSound(soundfile) {
document.getElementById("dummy").innerHTML=
"<embed src=\""+soundfile+"\" hidden=\"true\" autostart=\"true\" loop=\"false\" />";
}
</script>


<a href="#" onclick="playSound('URL to soundfile');">Click here to hear a sound</a>

<p onmouseover="playSound('URL to soundfile');">Mouse over this text to hear a sound</p>

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.