简体   繁体   中英

How to add Html Audio element using c# code

On an asp button's onClick event, I want to play a song on client. I have written the following code for doing so..

protected void btn1_Click(object sender, EventArgs e)
{
    HtmlGenericControl myAudio = new HtmlGenericControl("audio");
    myAudio.Attributes.Add("autoplay", "true");
    myAudio.Attributes.Add("hidden", "true");
    myAudio.Attributes.Add("src", Server.MapPath("~/Songs/") + "1.wav");
    myDivTag.Controls.Add(myAudio);
}

The Html is as follows :

<div id="myDivTag" runat="server"></div>

But even after the code is executed the div tag remains empty, And the song is not played. What am i doing wrong?

It's not an answer, but I can't comment. Have you tried if the path is correct? Is the ASP.NET-Control needed? How about http://www.w3schools.com/html/html5_audio.asp ?

Code of it:

<!DOCTYPE html>
<html>
  <body>
    <audio controls>
      <source src="horse.ogg" type="audio/ogg">
      <source src="horse.mp3" type="audio/mpeg">
    Your browser does not support the audio element.
    </audio>
  </body>
</html>

your html like this

<div runat="server" id="myDivTag">
    <audio autoplay runat="server" id="myaudio">
        <source src="" runat="server" type="audio/mpeg">
        <p>If you can read this, your browser does not support the audio element.</p>
    </audio>
</div>

and your button click event like this

protected void btn1_Click(object sender, EventArgs e)
{
  myaudio.Src = "~/new.mp3";
}

music playing in backend. so you can not pause music or stop it.

if you pause your music then some custom logic needed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM