I need a simple Google Speech API example for .NET in which I upload a voice file and receive the text.
Thanks.
Just worked for me, you can create a class as follow:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
namespace GoogleAPI{
public class GoogleSpeech
{
public string URL { get; set; }
public void GetSpeechTranscript(string filePath)
{
try
{
FileStream fileStream = File.OpenRead(filePath);
MemoryStream memoryStream = new MemoryStream();
memoryStream.SetLength(fileStream.Length);
fileStream.Read(memoryStream.GetBuffer(), 0, (int)fileStream.Length);
byte[] resBytes = memoryStream.GetBuffer();
HttpWebRequest request = null;
request = (HttpWebRequest)HttpWebRequest.Create(this.URL + "&key=YOUR_API_KEY");
request.Credentials = CredentialCache.DefaultCredentials;
request.Method = "POST";
request.ContentType = "audio/x-flac; rate=44100";
request.ContentLength = resBytes.Length;
Stream stream = request.GetRequestStream();
stream.Write(resBytes, 0, resBytes.Length);
stream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
StreamReader reqStream = new StreamReader(response.GetResponseStream());
var result = reqStream.ReadToEnd();
Console.WriteLine(result);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
Console.ReadLine();
}
}
}
Hope this help!
Related
Hello there fellow programmers!
I have an issue with sending PDF through FTP. I want to copy propely created PDF to FTP directory, unfortunately file i send through has proper size but i cannot open it with any PDF editor. I've tried searching soulutions but my converting and encoding does not seem to work. Here is my code:
public string SendPDF(string FileNamePath, string ShortFileName)
{
string Response = string.Empty;
//FullPath is generated in class constructor
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(FullPath+#"\"+ShortFileName+".pdf");
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential(User, Password);
//FileNamePath is directory of source file
byte[] fileContents= File.ReadAllBytes(#FileNamePath + ".pdf");
string pdfBase64 = Convert.ToBase64String(fileContents);
using(var stream = GenerateStreamFromString(pdfBase64))
{
request.ContentLength = stream.Length;
using (Stream requestStream = request.GetRequestStream())
{
stream.CopyTo(requestStream);
requestStream.Close();
}
}
using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
{
Response = "Upload File PDF Complete, status" + Convert.ToString(response.StatusDescription);
}
return Response;
}
public static Stream GenerateStreamFromString(string s)
{
var stream = new MemoryStream();
var writer = new StreamWriter(stream);
writer.Write(s);
writer.Flush();
stream.Position = 0;
return stream;
}
Also, I've tried code below but it has the same issue:
byte[] fileContents ;
using (StreamReader sourceStream = new StreamReader(FileNamePath + ".pdf"))
{
fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
}
request.ContentLength = fileContents.Length;
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(fileContents, 0, fileContents.Length);
}
Sending through XML file works completely fine. Thank you in advance and please don't be harsh this is my first question here :3
I found the solution. The issue was lack of parameter request.UseBinary = true. Here is proper code:
public string SendPDF(string FileNamePath, string ShortFileName)
{
string Response = string.Empty;
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(FTPPath+#"\"+ShortFileName+".pdf");
request.Method = WebRequestMethods.Ftp.UploadFile;
request.UseBinary = true;
request.Credentials = new NetworkCredential(User, Password);
byte[] fileContents;
using (StreamReader sourceStream = new StreamReader(FileNamePath + ".pdf"))
{
fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
}
request.ContentLength = fileContents.Length;
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(fileContents, 0, fileContents.Length);
}
using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
{
Response = "Upload File PDF Complete, status" + Convert.ToString(response.StatusDescription);
}
return Response;
}
I'm new to ASP.NET development and the use of webhooks.
I'm using ASP.NET and an Azure Automation Account which has a webhook. I can currently execute the webhook, however I would like to have my code wait until it receives the output of the webhook. How best to do this?
ASP.NET Code:
public ActionResult UpdateAll()
{
(random db calls)
string jsonList = JsonConvert.SerializeObject(userEnvironmentList);
try
{
string uri = "webhook_url";
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
string data = jsonList;
request.Method = "POST";
request.ContentType = "text/plain;charset=utf-8";
System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
byte[] bytes = encoding.GetBytes(data);
request.ContentLength = bytes.Length;
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(bytes, 0, bytes.Length);
}
request.BeginGetResponse((x) =>
{
using (HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(x))
{
using (Stream stream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(stream, Encoding.UTF8);
String responseString = reader.ReadToEnd();
}
}
}, null);
}
catch (Exception ex)
{
throw ex;
}
return View();
}
PS in Automation Account:
param
(
[Parameter (Mandatory = $false)]
[object] $WebhookData
)
if ($WebhookData) {
return "Finally this works"
}
Call GetResponse in a synchronized context then.
Change ...
request.BeginGetResponse((x) =>
{
using (HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(x))
{
using (Stream stream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(stream, Encoding.UTF8);
String responseString = reader.ReadToEnd();
}
}
}, null);
To ...
var response = (HttpWebResponse)webRequest.GetResponse();
using (Stream stream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(stream, Encoding.UTF8);
String responseString = reader.ReadToEnd();
}
note: GetResponse() waits till the underlying web request finishes, then it returns the result. no need to use BeginGetResponse() in your code context.
The following code should log user in, but it does not work. The code uses 9gag as an example, but the general idea should work elsewhere too. The user does not get access his/hers profile.
What is wrong with the code?
using System;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
namespace ttp_B
{
internal class Program
{
private static void Main(string[] args)
{
bool flag = false;
//string word_to_stop = "profile";
string urltosite = "https://9gag.com/login"; // site that i'm trying to log in
string emailaddress = "";
string password = "";
var coo = new System.Net.CookieContainer();
try
{
var request = System.Net.WebRequest.Create(urltosite) as System.Net.HttpWebRequest;
request.CookieContainer = coo;
request.Method = "POST";
request.Proxy = new WebProxy("127.0.0.1", 8888); // fiddler
//some extra headers
request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
request.UserAgent = "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:43.0) Gecko/20100101 Firefox/43.0";
using (var stream = request.GetRequestStream())
{
byte[] buffer =
Encoding.UTF8.GetBytes(
string.Format(
"csrftoken=&next=http%3A%2F%2F9gag.com%2F&location=1&username={0}&password={1}", emailaddress, password));
//this text of request is correct I guess. Got it from fiddler btw.
stream.Write(buffer, 0, buffer.Length);
stream.Close();
}
using (var response = request.GetResponse() as HttpWebResponse)
{
coo.Add(response.Cookies); // adding cookies, just to make this working properly
using (var sr = new System.IO.StreamReader(response.GetResponseStream()))
{
string http_code = sr.ReadToEnd(); // gettin' that new html document
//flag = (http_code.Contains(word_to_stop)); // looking for word that I'm sure exist after succesfull loggin' in
//if(flag == true)
//{
// console.writeline("Works");
//}
}
}
}
catch (WebException e)
{
Console.Write(e.ToString());
}
}
}
}
As far as I can see, the request stream isn't closed before you go for the response.
simplified it should look like this:
var stream = request.GetRequestStream();
tStream(buffer, 0, buffer.Length);
//close the stream
tStream.Close();
//go for the response
request.GetResponse();
I want to get the audio file from c# and send to google speech recognition API for get the "speech to text" answer.
My code is like this:
try
{
byte[] BA_AudioFile = GetFile(filename);
HttpWebRequest _HWR_SpeechToText = null;
_HWR_SpeechToText =
(HttpWebRequest)HttpWebRequest.Create(
"https://www.google.com/speech-api/v2/recognize?output=json&lang=" + DEFAULT_LANGUAGE + "&key=" + key);
_HWR_SpeechToText.Credentials = CredentialCache.DefaultCredentials;
_HWR_SpeechToText.Method = "POST";
_HWR_SpeechToText.ContentType = "audio/x-flac; rate=44100";
_HWR_SpeechToText.ContentLength = BA_AudioFile.Length;
Stream stream = _HWR_SpeechToText.GetRequestStream();
stream.Write(BA_AudioFile, 0, BA_AudioFile.Length);
stream.Close();
HttpWebResponse HWR_Response = (HttpWebResponse)_HWR_SpeechToText.GetResponse();
if (HWR_Response.StatusCode == HttpStatusCode.OK)
{
StreamReader SR_Response = new StreamReader(HWR_Response.GetResponseStream());
Console.WriteLine(SR_Response.ToString());
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
This part is for upload the file.wav and get the response for the google API, which I find from Internet.
But my code always catches the exceptions:
you must write content length bytes to the request stream before calling at _HWR_SpeechToText.GetResponse(); But I already wroteh the ContextLength.
So my question is why my program failed? It's because the google link or the HTTPWebRequest I used inappropriately?
Is this the right place I got the API key?
Just tested this myself, below is a working solution if you have a valid API key.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.IO;
namespace GoogleRequest
{
class Program
{
static void Main(string[] args)
{
try
{
FileStream fileStream = File.OpenRead("good-morning-google.flac");
MemoryStream memoryStream = new MemoryStream();
memoryStream.SetLength(fileStream.Length);
fileStream.Read(memoryStream.GetBuffer(), 0, (int)fileStream.Length);
byte[] BA_AudioFile = memoryStream.GetBuffer();
HttpWebRequest _HWR_SpeechToText = null;
_HWR_SpeechToText =
(HttpWebRequest)HttpWebRequest.Create(
"https://www.google.com/speech-api/v2/recognize?output=json&lang=en-us&key=YOUR_API_KEY_HERE");
_HWR_SpeechToText.Credentials = CredentialCache.DefaultCredentials;
_HWR_SpeechToText.Method = "POST";
_HWR_SpeechToText.ContentType = "audio/x-flac; rate=44100";
_HWR_SpeechToText.ContentLength = BA_AudioFile.Length;
Stream stream = _HWR_SpeechToText.GetRequestStream();
stream.Write(BA_AudioFile, 0, BA_AudioFile.Length);
stream.Close();
HttpWebResponse HWR_Response = (HttpWebResponse)_HWR_SpeechToText.GetResponse();
if (HWR_Response.StatusCode == HttpStatusCode.OK)
{
StreamReader SR_Response = new StreamReader(HWR_Response.GetResponseStream());
Console.WriteLine(SR_Response.ReadToEnd());
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
Console.ReadLine();
}
}
}
I want to know if there is someone who had use a Class to Call a WebService, this WS receives an integer after the organizational references and responds into a json file,
Actually my issue is to call the webservice without using a webreference, and read the json file and parse it into a dictionary ,
I appreciate your help
Best Regards, i let you my code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Net;
using Dimex.ChangeSAP.Core.Utilities;
namespace Dimex.ChangeSAP.Core.Utilities
{
class ConsumirWebService
{
public void ConsumirWS()
{
Dimex.ChangeSAP.Core.Entities.Seguridad.Usuario users = new Dimex.ChangeSAP.Core.Entities.Seguridad.Usuario();
int idUsuaro = users.IdUsuario;
try
{
System.Net.WebRequest req = System.Net.WebRequest.Create("http://192.168.8.97/PassportPruebas/api/partners?enterprise_system_id=1&organizational_reference=" + idUsuaro);
//req.Proxy = new System.Net.WebProxy(ProxyString, true);
//Add these, as we're doing a POST
req.ContentType = "application/x-www-form-urlencoded";
req.Method = "POST";
//We need to count how many bytes we're sending.
//Post'ed Faked Forms should be name=value&
string postData = "OPERATION_NAME=ADD_REQUEST&TECHNICIAN_KEY=90BA&INPUT_DATA=" + sendXML;
byte[] bytes = System.Text.Encoding.ASCII.GetBytes(postData);
req.ContentLength = bytes.Length;
System.IO.Stream os = req.GetRequestStream();
os.Write(bytes, 0, bytes.Length); //Push it out there
os.Close();
System.Net.WebResponse resp = req.GetResponse();
if (resp == null)
{
return null;
}
System.IO.StreamReader sr =
new System.IO.StreamReader(resp.GetResponseStream());
string respuesta = sr.ReadToEnd().Trim();
return respuesta;
}
catch (Exception ex)
{
return "";
//throw or return an appropriate response/exception
}
}
}
}
Well Actually here is my code for anyone with this kind of issue too,
public static string LlamarWebService(string url)
{
try
{
System.Net.WebRequest req = System.Net.WebRequest.Create(url);
req.ContentType = "application/json";
req.Method = "GET";
System.Net.WebResponse resp = req.GetResponse();
if (resp == null) return null;
System.IO.StreamReader sr =
new System.IO.StreamReader(resp.GetResponseStream());
string respuesta = sr.ReadToEnd().Trim();
return respuesta;
}
catch (Exception ex)
{
throw ex;
// return "";
//throw or return an appropriate response/exception
}
}
you can create a proxy class using wsdl utility or svcutil in visualstudiocommand prompt enter command wsdl.exe /out:[path and name of the file] /language:CS