audio record on web application using C# [duplicate] - c#

I want to play some sounds in my web page once I click a button. This is my code but it shows an error.
SoundPlayer x = new SoundPlayer();
x.SoundLocation = "WindowsBalloon.wav";
//x.Play();
x.PlaySync();
error:
Please be sure a sound file exists at the specified location.
but the file exists in my project and I'm sure that the address is correct.

You cannot play a file on a web page using the System.Media.Soundplayer class !!!
Reason
It will play sound on server-side not client-side.
As mentioned as in below links
- Problem With The C# System.Media.SoundPlayer Class On A Web Host
- What is the most “compatible” way of autoplaying sound ?
Solution
Other SO Answer over this same requirements.
Use Any other Flash or Silverlight based plugins.
Use html embed tag or html5 audio tag. Examples can be seen on w3schools
Html5-based audio solutions (works on modern browsers only)
<embed> tag: The <embed> tag defines a container for external (non-HTML) content. (It is an HTML5 tag, invalid in HTML 4, but works in all browsers).
<embed height="100" width="100" src="horse.mp3" />
<object> tag: The <object> tag can also define a container for external (non-HTML) content.
<object height="100" width="100" data="horse.mp3"></object>
<audio> tag: The <audio> element is an HTML5 element, invalid in HTML 4, but it works in all browsers.
<audio controls="controls" height="100" width="100">
<source src="horse.mp3" type="audio/mp3" />
<source src="horse.ogg" type="audio/ogg" />
<embed height="100" width="100" src="horse.mp3" />
</audio>
Please note the problems with html5-based solutions you must convert your videos to different formats.
- The <audio> element does not validate as HTML 4 and XHTML.
- The <embed> element does not validate as HTML 4 and XHTML.
- The <embed> element cannot "fall-back" to display an error.

You need to use <object> or <embed> html tags.
<object data="WindowsBalloon.wav"></object>
Or HTML5 tag
<audio src="WindowsBalloon.wav">
<p>Your browser does not support the audio element.</p>
</audio>

This works in HTML5 :
protected void Button1_Click(object sender, EventArgs e)
{
Response.Write("<embed height='0' width='0' src='Sound.wav' />");
}

This is what I think you want:
Server.MapPath(string path);
Returns the physical file path that corresponds to the specified virtual path on the Web server.
Parameters: path: The virtual path of the Web server.
Returns: The physical file path that corresponds to path.
SoundPlayer s = new SoundPlayer();<br>
s.SoundLocation = **Server.MapPath("WindowsBalloon.wav");**<br>
s.PlaySync();

Given full path i.e. c:\wavfiles\WindowsBalloon.wav
'wavfiles' above is a user privileged folder.
use x.PlayLooping()
function if you want to play sound file continuously
BE CAREFUL!
use one button to exit loop else sound file will run continuously. I suggest you to exit the loop: -
Code
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
x.Stop()
End Sub

If you need to play an ALARM sound programmatically you can do it this way:
<asp:Panel runat="server" ID="panBuzz" style="visibility:hidden">
<audio runat="server" id="Buzz" src="http://.....mp3" type="audio/mp3"/>
</asp:Panel>
Code behind (visual basic):
Dim cBuzz As HtmlControl = DirectCast(panBuzz.FindControl("Buzz"), HtmlControl)
cBuzz.Attributes.Add("autoplay", "autoplay")
Code behind (C#):
HtmlControl cBuzz = (HtmlControl)panBuzz.FindControl("Buzz");
cBuzz.Attributes.Add("autoplay", "autoplay");

try adding the drive letter to the path, such as "C:/WindowsBalloon.wav". But this would not play it on the client side. I would recomend trying HTML5 for the client side.

SoundPlayer s = new SoundPlayer();
s.SoundLocation = Server.MapPath("WindowsBalloon.wav");
s.PlaySync();

Related

Adding src Dynamically to img in C#

I have an img tag.
(I am using just image and not asp.net because it is an imageMap that I have working with an img).
I dynamically set the src as below in 3 different ways. The first way works and the image is included in the project. But when I try to add the src the 2nd way it fails to display the image. That image is not part of the project. I have even tried the 3rd way for a different location but it fails to load as well. It is not part of the project either. What I need to be able to do is load ans image src dynamically that is not included in the project and have it display.
<img runat="server" class="ImageMap" id="ImageMapID" src="" usemap="#imagemap" />
ImageMapID.Attributes["src"] = #"/Icons/XXXX XXXX.png";//first way that works
ImageMapID.Attributes["src"] = #"/documents/XXXXX/XXXX_04092017.pdf"; // second way that fails
ImageMapID.Attributes["src"] = #"file://C:/temp/XXXXXXXX.pdf";// third way that fails
Any ideas anybody? I should add they are different images but they should all work.
First thing you should know, PDF files are not image objects, so you can't use img tag to embed it. You need to use iframe tag instead:
<iframe src="file:///C:/temp/XXXXXXXX.pdf" style="width: 100%; height: 100%;" frameborder="0" scrolling="no">
...
</iframe>
Or use embed/object tag with same file path:
<embed src="file:///C:/temp/XXXXXXXX.pdf" width="600" height="400" type="application/pdf">
<object type="application/pdf" data="file:///C:/temp/XXXXXXXX.pdf" title="XXXXX" width="600" height="400" >...</object>
If you want to include local file path for images, use file reference path or relative path with proper directory structure shown in example below:
ImageMapID.Attributes["src"] = #"file:///C:/temp/Icons/XXXXXXXX.png";
// watch out for current relative path you're using
ImageMapID.Attributes["src"] = #"../../temp/Icons/XXXXXXXX.png";
Note that Windows local drive path uses this format to refer any files for use in any HTML elements with source attribute:
file:///[drive letter]:/[path_to_resource]/[filename].[extension]
References:
How to properly reference local resources in HTML?
Recommended way to embed PDF in HTML?

How can I embed <iframe> HTML code into C# application?

how can I embed a HTML iframe into my c# application most efficiently.
Let's say this youtube video:
<iframe width="560" height="315" src="//www.youtube.com/embed/UJ53Js0YKZM" frameborder="0" allowfullscreen></iframe>
I have tried this one but did not work:
Private Sub InitializeComponent()
Dim resources As System.ComponentModel.ComponentResourceManager = New System.ComponentModel.ComponentResourceManager(GetType(frmAbout))
'
'frmVirtual
'
Me.Text = "Virtual"
Me.VirtualView = New WebBrowser
Me.VirtualView.Navigate("<iframe src='https://www.google.com/maps/embed?pb=!1m0!3m2!1sen!2sau!4v1481252003737!6m8!1m7!1sF%3A-pwYGx-oWTIk%2FWC6LeJuIxdI%2FAAAAAAAABIg%2FphppDvMZr54JiWnLbsbUgDcTGUfGXLMRACLIB!2m2!1d-33.76525136331761!2d150.9088391438127!3f310!4f0!5f0.7820865974627469' width='600' height='450' frameborder='0' style='border: 0' allowfullscreen></iframe>")
Me.SuspendLayout()
End Sub
The C# application would be a Windows Form Application of course. It doesn't necessarly has to be a video, but even just a small banner with link, in an Iframe of course. Please help!
You can use the WebBrowser control accomplish this.
WebBrowser1.Navigate("https://www.youtube.com/embed/UJ53Js0YKZM?autoplay=1");
You cannot use an IFrame in a windows form application. There is however a windows form control named System.Windows.Forms.WebBrowser();
This can be used by navigating to toolbox (whilst on a win forms designer) and dragging on a web browser (Common Controls).
In the Form's class you need something like the following.
public Form1()
{
InitializeComponent();
webBrowser1.Navigate("www.youtube.com/embed/UJ53Js0YKZM");
}
If you really want a iframe the following may work
private void Form1_Load(object sender, EventArgs e)
{
var page = #"
<html>
<body>
<iframe width='560' height='315'
src='https//www.youtube.com/embed/UJ53Js0YKZM' frameborder='0'>
</iframe>
</body>
<html>";
webBrowser1.DocumentText = page;
webBrowser1.ScriptErrorsSuppressed = true;
}
If you only want to access the one youtube video, you can save that iframe code inside an otherwise empty html document and point the webBrowser to that.
string applicationDirectory = System.IO.Path.GetDirectoryName(Application.ExecutablePath);
string myFile = System.IO.Path.Combine(applicationDirectory, "iFrame.html");
webBrowser1.Url = new Uri("file:///" + myFile);
If you want to have a more robust approach, you can build the iframe's html and send that as a string to the webBrowser's document. See How to display the string html contents into webbrowser control? for information on how to do that.
I have Windows 10 and a C#, UWP app. If you want to just show the contents (URL) of an iFrame, this worked for me. There was no need to write code in my xaml.cs file, since I only wanted to show a website.
<Grid>
<WebView Source ="https://yourwebsite.com" Height="250" Width="650" />
</Grid>
The original iFrame was this:
<iframe style="height:250px; width:650px" src="https://yourwebsite.com></iframe>
For a YouTube video:
<Grid>
<WebView Source ="https://www.youtube.com/embed/jJKEkZL9qrM" Height="250" Width="650" />
</Grid>
<iframe visible="true" runat="server" id="yourid" style="visibility:hidden;display:block;width:1px;height:1px;"></iframe>
yourid.Attributes.Add("src", "youtube.com");

ASP.NET: Call .swf in .aspx page

I'm trying the code below but its not working..
<object width="425" height="344">
<embed src="C:\Users\fortress\Desktop\AppointmentApp.swf" type="application/x-shockwave-flash" width="425" height="344"></embed>
</object>
Also tried this. Not working also.
<object width="425" height="344">
<embed src="~/Styles/Images/AppointmentApp.swf" type="application/x-shockwave-flash" width="425" height="344"></embed>
</object>
Problem:
The swf is not displaying.
I saw an error when I open the designer saying that "A control type was not specified or the specified type could not be found." I already import the shockwave-player for flash but still this error appeared..
I want also that the .swf will be fullscreen played in .aspx.
I'm newbie in ASP.net.. SO yeah, please explain also the code if its okay...
Here's the output in client-side:
Here's the whole code for my client-side:
Thanks!
This isn't ASP.NET, this is HTML. It might be served to the client by an ASP.NET server-side application, but that makes no difference to the client.
As far as HTML goes, your paths are broken. In both cases:
C:\Users\fortress\Desktop\AppointmentApp.swf
~/Styles/Images/AppointmentApp.swf
In the first case you're referencing a file system path. This wouldn't work on any client computer which doesn't have that file. If the file is on the web server then no client will be able to access the web server's C: drive. In the second case you're using a server-side relative path with a ~, and no client will be able to make sense of that.
When the page renders, the path needs to reference the file from the client's perspective. Something like this:
/Styles/Images/AppointmentApp.swf
Or perhaps:
../../Styles/Images/AppointmentApp.swf
Or whatever the path is from the rendered page to the SWF file.
I'm not 100% sure if this works well for object/embed tags, but you might be able to use the ~ path reference if you make the tag a server-side control. That should just be as easy as adding runat="server" to the tag:
<embed runat="server" src="~/Styles/Images/AppointmentApp.swf" type="application/x-shockwave-flash" width="425" height="344"></embed>
This would indicate to the ASP.NET application that the control needs some server-side processing before it's rendered to the client, and that processing would include evaluating relative paths.
You need both <param> movie tag and <embed>. Try this:
<object type="application/x-shockwave-flash" width="425" height="344">
<param name="movie" value="/Styles/Images/AppointmentApp.swf">
<embed src="/Styles/Images/AppointmentApp.swf" type="application/x-shockwave-flash" width="425" height="344"></embed>
</object>
Good luck!

How to play youtube videos on windows application C#

I've created a windows application with a WebBrowser control and trying to play youtube videos.. I've installed Adobe Shockwave Player, and tried to watch video on my windows application, but it doesn't show any videos. When I hit play button the screen looks like this
My code for playing video is
StreamWriter sw = new StreamWriter("utube.html");
string PlayString = currentVideoUrl.Trim().Replace("watch?v=", "v/");
string Finalplaycode = "<embed src=" + PlayString + "&hl=en&fs=1& type=application/x-shockwave-flash allowscriptaccess=always allowfullscreen=true width=425 height=344></embed>";
sw.Write(Finalplaycode);
sw.Close();
string PathToNavigate = Directory.GetParent(Application.ExecutablePath) + #"\utube.html";
webBrowser1.Navigate(PathToNavigate);
and my example video link is : http://www.youtube.com/watch?v=oZdnezj9Dfg&feature=BFa&list=PLD3E900BFF6534896&lf=plpp_video
can anyone help me about this issue? Did I missing any plug-in or something? I am using .NetFramework 4.0
One problem I see is that you're not quoting the parameters in the embed. Your embed will generate as:
<embed src=http://www.youtube.com/v/video_id...>
You need to quote those parameters:
<embed src="http://www.youtube.com/v/video_id...">
For example, here's an embed that works on my site:
<embed type="application/x-shockwave-flash" width="425" height="344"
src="http://www.youtube.com/v/UejelYnVI3U&hl=en&fs=1"></embed>
You might be interested in reading the official YouTube documentation. They've moved away from using embeds, in favor of iframes. That lets them use the HTML5 video player if it's available, or otherwise fall back to Flash. See http://www.google.com/support/youtube/bin/answer.py?answer=171780 for details.
Update:
The HTML file below embeds the same video in two ways: once using the iframe and once using the standard embed. It works find when I navigate to it with the WebBrowser control:
<html>
<body>
<iframe class="youtube-player" type="text/html" width="640" height="385"
src="http://www.youtube.com/embed/oZdnezj9Dfg" frameborder="0">
</iframe>
<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="425" height="344"
codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0">
<param name="src" value="http://www.youtube.com/v/oZdnezj9Dfg&hl=en&fs=1" />
<embed type="application/x-shockwave-flash" width="425" height="344"
src="http://www.youtube.com/v/oZdnezj9Dfg&hl=en&fs=1">
</embed>
</object>
</body>
<html>
Try copying that and navigating to it in your application. Make sure that your program is creating the embed just like that.
Also, you can remove the outer <object> tag if you already have Flash installed. Then, the Flash embed looks just like what I showed originally.
And, there's no requirement that you have the HTML wrapper around it. It works fine if I just include the embed without the <html> and other tags.

How can I get a web site's favicon?

Simple enough question: I've created a small app that is basically just a favourites that sits in my system tray so that I can open often-used sites/folders/files from the same place. Getting the default icons from my system for known file types isn't terribly complicated, but I don't know how to get the favicon from a website. (SO has the grey->orange stack icon in the address bar for instance)
Does anyone know how I might go about that?
You'll want to tackle this a few ways:
Look for the favicon.ico at the root of the domain
www.domain.com/favicon.ico
Look for a <link> tag with the rel="shortcut icon" attribute
<link rel="shortcut icon" href="/favicon.ico" />
Look for a <link> tag with the rel="icon" attribute
<link rel="icon" href="/favicon.png" />
The latter two will usually yield a higher quality image.
Just to cover all of the bases, there are device specific icon files that might yield higher quality images since these devices usually have larger icons on the device than a browser would need:
<link rel="apple-touch-icon" href="images/touch.png" />
<link rel="apple-touch-icon-precomposed" href="images/touch.png" />
And to download the icon without caring what the icon is you can use a utility like http://www.google.com/s2/favicons which will do all of the heavy lifting:
var client = new System.Net.WebClient();
client.DownloadFile(
#"http://www.google.com/s2/favicons?domain=stackoverflow.com",
"stackoverflow.com.ico");
Updated 2020
Here are three services you can use in 2020 onwards
<img height="16" width="16" src='https://icons.duckduckgo.com/ip3/www.google.com.ico' />
<img height="16" width="16" src='http://www.google.com/s2/favicons?domain=www.google.com' />
<img height="16" width="16" src='https://api.statvoo.com/favicon/?url=google.com' />
You can use Google S2 Converter.
http://www.google.com/s2/favicons?domain=google.com
Source: http://www.labnol.org/internet/get-favicon-image-of-websites-with-google/4404/
This question is the first google search result I got when I keep searching for website favicon API. So I think it'll be still helpful in the future.
https://icon.horse/icon/[url.hostname] will give you a better site icon.
https://icon.horse/icon/stackoverflow.com
You can do it without programming in 3 steps:
1. Just open the web site, right-click and select "view source" to open the HTML code of that site. Then in the text editor search for "favicon" - it will direct you to something looking like
<link rel="icon" href='/SOMERELATIVEPATH/favicon.ico' type="image/x-icon" />
Take the string in href and append it to the web site's base URL (let's assume it is "http://WEBSITE/"), so it looks like
http://WEBSITE/SOMERELATIVEPATH/favicon.ico
which is the absolute path to the favicon. If you didn't find it this way, it can be as well in the root in which case the URL is http://WEBSITE/favicon.ico.
2. Take the URL you determined and insert it into the href-Parameter of the following code:
<html>
<head>
<title>Capture Favicon</title>
</head>
<body>
<a href='http://WEBSITE/SOMERELATIVEPATH/favicon.ico' alt="Favicon"/>Favicon</a>
</body>
</html>
3. Save this HTML code locally (e.g. on your desktop) as GetFavicon.html and then double-click on it to open it. It will display only a link named Favicon. Right-click on this link and select "Save target as..." to save the Favicon on your local PC - and you're done!
It's a good practice to minimize the number of requests each page needs.
So if you need several icons, yandex can do a sprite of favicons in one query.
Here is an example
http://favicon.yandex.net/favicon/google.com/stackoverflow.com/yandex.net/
The first thing to look for is /favicon.ico in the site root; something like WebClient.DownloadFile() should do fine. However, you can also set the icon in metadata - for SO this is:
<link rel="shortcut icon"
href="http://sstatic.net/stackoverflow/img/favicon.ico">
and note that alternative icons might be available; the "touch" one tends to be bigger and higher res, for example:
<link rel="apple-touch-icon"
href="http://sstatic.net/stackoverflow/img/apple-touch-icon.png">
so you would parse that in either the HTML Agility Pack or XmlDocument (if xhtml) and use WebClient.DownloadFile()
Here's some code I've used to obtain this via the agility pack:
var favicon = "/favicon.ico";
var el=root.SelectSingleNode("/html/head/link[#rel='shortcut icon' and #href]");
if (el != null) favicon = el.Attributes["href"].Value;
Note the icon is theirs, not yours.
In 2020, using duckduckgo.com's service from the CLI
curl -v https://icons.duckduckgo.com/ip2/<website>.ico > favicon.ico
Example
curl -v https://icons.duckduckgo.com/ip2/www.cdc.gov.ico > favicon.ico
You can get the favicon URL from the website's HTML.
Here is the favicon element:
<link rel="icon" type="image/png" href="/someimage.png" />
You should use a regular expression here. If no tag found, look for favicon.ico in the site root directory. If nothing found, the site does not have a favicon.
HttpWebRequest w = (HttpWebRequest)HttpWebRequest.Create("http://stackoverflow.com/favicon.ico");
w.AllowAutoRedirect = true;
HttpWebResponse r = (HttpWebResponse)w.GetResponse();
System.Drawing.Image ico;
using (Stream s = r.GetResponseStream())
{
ico = System.Drawing.Image.FromStream(s);
}
ico.Save("favicon.ico");
Sometimes we can't get the favicon image with the purposed solution as some websites use .png or other image extensions. Here is the working solution.
Open your website with a firefox browser.
Right-click on the website and click the "View page info" option from the list.
It will open up a dialog and click on the "Media" tab.
In that tab you will see all the images including favicon.
Select the favicon.ico image or click through the images to see which image is used as favicon. Some websites use .png images as well.
Then click on the "Save As" button and you should be good to go.
thanks!
This is a late answer, but for completeness: it is difficult to get even close to fetching 90% all favicons.
A while ago I wrote a WordPress plugin which attempts to get closer to 100%.
This is how it works:
It starts by searching existing favicon repositories such as Google favicons and GetFavicons for the favicon.
If none of them returns an icon, the plugin attempts to get the icon itself. This involves traversing several pages on the domain.
The plugin then inspects the physical image file, because on some servers files get returned with the incorrect mime types.
The code is still not perfect because in the details you will find many weird situations: people have wrongly coded paths, e.g. img/favicon.ico where img is not in the root, duplicate headers in HTML output, different server responses from the head and body etc.
The core of the fetching part is here so you can reverse-engineer it, but be aware that validating the response should be done (checking image filetype, mime etc.).
The SHGetFileInfo (Check pinvoke.net for the signature) lets you retrieve a small or large icon, just as if you were dealing with a file/folder/Shell item.
http://realfavicongenerator.net/favicon_checker?site=http://stackoverflow.com gives you favicon analysis stating which favicons are present in what size. You can process the page information to see which is the best quality favicon, and append it's filename to the URL to get it.
You can use Getfv.co :
To retrieve a favicon you can hotlink it at... http://g.etfv.co/[URL]
Example for this page : http://g.etfv.co/https://stackoverflow.com/questions/5119041/how-can-i-get-a-web-sites-favicon
Download content and let's go !
Edit :
Getfv.co and fvicon.com look dead. If you want I found a non free alternative : grabicon.com.
Using jquery
var favicon = $("link[rel='shortcut icon']").attr("href") ||
$("link[rel='icon']").attr("href") || "";

Categories