Snippets below have been condensed from their original sources for brevity. See references for original articles.
All examples are in C# .Net.
Winforms:
public static enum SoundSource {
FromFileSystem = 0,
FromResourceStream=1
}
public static void PlaySound(string Filename, SoundSource Source) {
switch (Source) {
case SoundSource.FromFileSystem:
SoundPlayer objPlayer = new SoundPlayer();
objPlayer.SoundLocation="C:\\" + Filename;
objPlayer.Play();
break;
case SoundSource.FromResourceStream:
SoundPlayer objPlayer2 = new SoundPlayer();
objPlayer2.Stream = GetEmbeddedResourceStream(Filename);
objPlayer2.Play();
break;
}
}
private static System.IO.Stream GetEmbeddedResourceStream(string FileName) {
Assembly objAssembly;
System.IO.Stream soundstream;
objAssembly = Assembly.LoadFrom();
soundstream = objAssembly.GetManifestResourceStream(FileName);
return soundstream;
}
ASP .Net: (create an empty div in your page called “sound_element”)
public static void PlaySound(Page PageInstance)
{
ClientScriptManager ClientScript = PageInstance.ClientScript;
string soundclipscript =
"<script type=\"text/javascript\">" +
"$('#sound_element').html(\"<embed src='\"+ PageInstance.ResolveUrl(\"~\") + "Sounds/ambient1.mp3" +\"' hidden=true autostart=true loop=false>\");" +
"</script>";
AjaxControlToolkit.ToolkitScriptManager.RegisterStartupScript(PageInstance, PageInstance.GetType(), "playsound",
soundclipscript, false);
}
Note there are many ways to play audio in a page, and the above snippet is not necessarily the best approach for every browser.
New HTML5 audio tag:
<audio src="horse.ogg" controls="controls"> Your browser does not support the audio element. </audio>
References
dotnetspider, http://www.dotnetspider.com/resources/5014-Play-Audio-File-Wav.aspx
W3C Schools, http://www.w3schools.com/html5/tag_audio.asp
Leave a comment