Mhmt
Mhmt

Reputation: 769

How to add <audio> tag to Content of Page in Code behind?

I want to add this audio html tag to the page from code behind in Client.RegisterClientScriptBlock(). Is it possible?

<audio id="A"></audio>
<script type="text/javascript">
    var player = document.getElementById("A");
    function Alert() {
        player.preload = 'auto';
        player.src = "/Sounds/tada.wav";
        player.play();
    }
</script>

BaseClass

public class BasePage : System.Web.UI.Page
{

protected override void OnPreRender(EventArgs e)
{
   base.OnPreRender(e);

  //add audio tag 

}

}

Page.aspx

 <asp:Content ID="Content1" ContentPlaceHolderID="MainContent"  runat="server">
 ....
 .....
 ....
</asp:Content>

Page.aspx.cs

public partial class Page: BasePage
{
   protected void Page_Load(object sender, EventArgs e)
    {  }

}

Upvotes: 1

Views: 2037

Answers (2)

Jonathan
Jonathan

Reputation: 5018

<audio> tag? or <html> tag?

<audio> tag you should be able to add with

var ctrl = new HtmlGenericControl("audio");
myContainer.Add(ctrl);

where myContainer is a container in your template (eg a div)

For the javascript part, you would need to reference the client id of the audio ctrl in your javascript. You could build up your javascript in the backend, or just build up a javascript property in the backend and put it into the template.

var scriptText = String.Format("var audioId = {0};", ctrl.ClientId);
ClientScript.RegisterClientScriptBlock(this.GetType(), "MyScript", scriptText, true);

and then in your javascript in the template

var player = document.getElementById(audioId); 

Upvotes: 3

codeandcloud
codeandcloud

Reputation: 55248

You can use this

var myAudio = new System.Web.UI.HtmlControls.HtmlAudio();
myAudio.Attributes.Add("autoplay", "autoplay");
myAudio.Attributes.Add("controls", "controls");
myAudio.Src = "test.mp3";
Form.Controls.Add(myAudio);

Upvotes: 0

Related Questions