Cannot hear audio from ASP.NET "Text to Speech" Application - asp.net

in my asp.net project, I code below for a text to speech function.
in my page's c# file.
byte[] SpeakText(string text)
{
using (SpeechSynthesizer s = new SpeechSynthesizer())
{
using (MemoryStream ms = new MemoryStream())
{
s.SetOutputToWaveStream(ms);
s.Speak(text);
return ms.GetBuffer();
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
if (TextBox1.Text != "")
{
Response.Write(SpeakText(TextBox1.Text));
}
}
but not hear the audio while run it.
How to solve the problem?

Try setting the response content type:
Response.ContentType = "audio/wav";
Also don't use Response.Write as it expects encoded characters. You need to write binary to avoid getting corrupt data:
Response.Clear();
Response.ContentType = "audio/wav";
Response.BinaryWrite(SpeakText(TextBox1.Text));
Response.End();

your code is executing on the server, not on the client machine.
Once you have generated the Speech output you should stream it down to the client (as a wav file for example), check this answer for a full example:
https://stackoverflow.com/a/1719867/559144

Related

How to flush xml file in asp.net?

I want to return a xml file to a client, and THEN perform my logic.
I try to use Response.Flush(), but it doesn't work correctly for me.
My code:
protected void Page_Load(object sender, EventArgs e)
{
string arg1= this.Request["arg1"];
string arg2= this.Request["arg2"];
string arg3= this.Request["arg3"];
var doc = new XmlDocument();
XmlNode responseNode = doc.CreateElement("response");
doc.AppendChild(responseNode);
var messageNode = responseNode.AppendChild(doc.CreateElement("message"));
messageNode.InnerText = "Your request is being processed";
Response.Clear();
Response.ContentType = "text/xml";
Response.ContentEncoding = System.Text.Encoding.UTF8;
doc.Save(Response.Output);
Response.Flush(); // I want to display xml in this moment but it doesn't work
LogicManager manager = new LogicManager();
manager.DoSth(arg1, arg2, arg3);
Response.End();
}
Response.End();
Generally, it is a bad idea to be using Response.End() in your code.
From the source: This method is provided only for compatibility with ASP—that is, for compatibility with COM-based Web-programming technology that preceded ASP.NET. If you want to jump ahead to the EndRequest event and send a response to the client, it is usually preferable to call CompleteRequest instead.
Given this info, instead of this:
Response.Flush(); // I want to display xml in this moment but it doesn't work
LogicManager manager = new LogicManager();
manager.DoSth(arg1, arg2, arg3);
Response.End();
do this:
Response.Flush(); // I want to display xml in this moment but it doesn't work
Response.CompleteRequest();
LogicManager manager = new LogicManager();
manager.DoSth(arg1, arg2, arg3);
// here you might want to make sure that no other page handlers are executed

How to Read the Content of a Remote Web Page Tag by Tag in asp.net using c#?

I want to read the content of the Remote Webpage in asp.net using C#. I have read it using the following code in asp.net.
protected void Page_Load(object sender, EventArgs e)
{
string TheUrl = "http://www.demosite.com/Default.aspx";
string response = GetHtmlPage(TheUrl);
Response.Write(response);
}
static string GetHtmlPage(string strURL)
{
String strResult;
WebResponse objResponse;
WebRequest objRequest = HttpWebRequest.Create(strURL);
objResponse = objRequest.GetResponse();
using (StreamReader sr = new StreamReader(objResponse.GetResponseStream()))
{
strResult = sr.ReadToEnd();
sr.Close();
}
return strResult;
}
Here i get the whole content of the Remote WebPage now i want read the content Tag by tag and get Only the Content of it. Is it possible?
Help Appreciated...!
Thanks in advance!
Use the HTML Agility pack to traverse the elements. It's the best way to parse HTML.
You should be able to get all the text nodes with
doc.DocumentNode.SelectNodes("//text()[normalize-space(.) != '']")

Download a string as a file in ASP.NET

The following method, based on code in this question, shows a file download dialog box in the browser, but then the download never starts (it stays at 0%):
protected void lnkExport_Click(object sender, EventArgs e) {
var bytes = Encoding.ASCII.GetBytes(SelectRecords()); //Data to be downloaded
Response.Clear();
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("Content-Disposition", "attachment; filename=\"test.xls\"");
using (var stream = new MemoryStream(bytes)) {
Response.AddHeader("Content-Length", stream.Length.ToString());
stream.WriteTo(Response.OutputStream);
}
}
Any idea what's up?
Your code worked fine for me but you may want to try adding this as the last line of your click handler:
Response.End();

Write PDF stream to response stream

I am having problems when I tried to run the following code from my asp.net page. The code is from another post (http://stackoverflow.com/questions/5828315/write-pdf-stream-to-response-stream). When the Test.pdf file is located in my local drive, I am not able to open the file when the open button on the dialog box is clicked. When, the save button is clicked, the file tries in as myAspPageName.pdf in "C:\Downloads" the operation goes on for ever without actually saving anything.
I am sure what I am doing wrong. Thanks for any help. Is there a better way of doing the same thing?
protected void Page_Load(object sender, EventArgs e)
{
Context.Response.Buffer = false;
FileStream inStr = null;
byte[] buffer = new byte[1024];
long byteCount; inStr = File.OpenRead(#"C:\Downloads\Test.pdf");
while ((byteCount = inStr.Read(buffer, 0, buffer.Length)) > 0)
{
if (Context.Response.IsClientConnected)
{
Context.Response.ContentType = "application/pdf";
Context.Response.OutputStream.Write(buffer, 0, buffer.Length);
Context.Response.Flush();
}
}
}
You can use Response.WriteFile instead of all the buffer work.
protected void Page_Load(object sender, EventArgs e)
{
Context.Response.WriteFile(#"C:\Downloads\Test.pdf");
}
Consider using HttpResponse.TransmitFile (ASP.NET >= 2.0), especially for large files because it writes the file without buffering it into server memory.
Also, make sure you always set the Response.ContentType property to the appropriate MIME type or browsers will sometimes have trouble with downloading your files correctly, especially if you are writing the file from a handler:
Response.ContentType = "application/pdf";

Silverlight OOB WebBrowser Exception

I've got an oob app with a webbrowser on it.
The webbrowser source is databound with a URI defined by me. The URI has a path to a webpage from my server that displays a PDF file from its hardrive.
Note that all this is done on a local network.
URI example: uri = new Uri(#"http://ServerName/ProjectName/PDFViewer.aspx?pdf=somePDF.pdf");
Page code-behind:
protected void Page_Load(object sender, EventArgs e)
{
string myURL = Request.Url.ToString();
string[] ParamArray = Regex.Split(myURL, "pdf=");
string Params = ParamArray[ParamArray.Length - 1];
if (Params.Length > 0)
{
Filename = Regex.Replace(Params, #"//", #"\\"); ;
if (File.Exists(Filename))
{
Response.ContentType = "Application/pdf";
Response.WriteFile(Filename); //Write the file directly to the HTTP content output stream.
Response.End();
}
else
this.Title = "PDF Not Found";
}
}
protected void Page_Load(object sender, EventArgs e) { string myURL = Request.Url.ToString(); string[] ParamArray = Regex.Split(myURL, "pdf="); //If the URL has parameters, then get them. If not, return a blank string string Params = ParamArray[ParamArray.Length - 1]; if (Params.Length > 0) { //to the called (src) web page Filename = Regex.Replace(Params, #"//", #"\\"); ; if (File.Exists(Filename)) { Response.ContentType = "Application/pdf"; Response.WriteFile(Filename); //Write the file directly to the HTTP content output stream. Response.End(); } else this.Title = "PDF Not Found"; } }
The first time I set the WebBrowser source everything it displays the PDF. But when I set the URI one second time the app throws an exception: Trying to revoke a drop target that has not been registered (Exception from HRESULT: 0x80040100).
I've done a few tests and here are the results:
1º new Uri(#"http://ServerName/ProjectName/PDFViewer.aspx?pdf=somePDF.pdf");
2º new Uri(#"http://ServerName/ProjectName/PDFViewer.aspx?pdf=someOtherPDF.pdf"); ->error
1º new Uri(#"http://ServerName/ProjectName/PDFViewer.aspx?pdf=somePDF.pdf");
2º new Uri(#"http://www.google.com"); ->error
1º new Uri(#"http://www.google.com");
2º new Uri(#"http://www.microsoft.com");
2º new Uri(#"http://ServerName/ProjectName/PDFViewer.aspx?pdf=somePDF.pdf");
3º new Uri(#"http://ServerName/ProjectName/PDFViewer.aspx?pdf=someOtherPDF.pdf"); ->error
I also forgot to say that when running the app from my browser (using a HTMLHost) the pages display just fine. Opening the pages using a browser will also work well.
It must be some problem with my aspx page. Any ideas?
Pedro
I've managed to resolve this by creating a new browser for each page. If you know of a more elegant solution please share.
I am not sure if I'm following the question/problem correctly but maybe loading the pages async and then assigning to webbrowser? Forgive me if I am off-base here.
public void ShowLink(string linkUrl)
{
if (App.Current.IsRunningOutOfBrowser)
{
var pageRequest = new WebClient();
pageRequest.DownloadStringCompleted += pageRequest_DownloadStringCompleted;
pageRequest.DownloadStringAsync(new Uri(linkUrl, UriKind.Absolute));
}
}
void pageRequest_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
webBrowserLink.NavigateToString(e.Result.ToString());
}

Resources