I'm using google speech recognition for speech to text of a audio file. Response i get as output shows only {"result":[]}. I don't see any output result.
i have picked my code from How to use google speech recognition api in c#? and Google speech to text API in C# . i have tried almost every answer in above links still i am getting the error.
My code is:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.IO;
using Newtonsoft.Json;
namespace google_api
{
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=mykey");
_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()+SR_Response.ToString());
string responseFromServer = (SR_Response.ReadToEnd());
String[] jsons = responseFromServer.Split('\n');
String text = "";
foreach (String j in jsons)
{
dynamic jsonObject = JsonConvert.DeserializeObject(j);
if (jsonObject == null || jsonObject.result.Count <= 0)
{
continue;
}
text = jsonObject.result[0].alternative[0].transcript;
}
Console.WriteLine("MESSAGE : "+text);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
Console.ReadLine();
}
}
}
Related
im using c# in my web. i m trying to upload a video in my website and im almost succed but the computer go to folder'C:\Program Files (x86)\IIS Express\' insted of just C:\Users\Omer\source\repos\WebApplication12\WebApplication12\potg. im using the function Server.MapPath(folder) and yet its dont work. help pls?
c#
string path = "";
MyVideoHelper x = new MyVideoHelper();
bool deleteFile = false;
if ((video2.PostedFile != null) && (video2.PostedFile.ContentLength > 0))
{
path =x.SaveFileInFoder(video2.PostedFile, "potg", Server);
deleteFile = true;
}
string potg = "potg";
string command = "INSERT INTO videos (file) VALUES('"+x.ConvertFileToByte(potg)+"')";
MyAdoHelper.DoQuery("omerwatchdb.accdb", command);
Response.Redirect("potg.aspx");
Response.End();
if ((deleteFile) && (File.Exists(path))){File.Delete(path);}
library:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
public class MyVideoHelper
{
public MyVideoHelper()
{
}
public byte[] ConvertFileToByte(string location)
{
byte[] video = null;
FileStream fs = new FileStream(location, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
video = br.ReadBytes((int)(fs.Length));
return video;
}
public string SaveFileInFoder(HttpPostedFile file, string folder, HttpServerUtility Server)
{
string location;
if (file != null && file.ContentLength > 0)
{
location = Server.MapPath(folder) + "\\" + System.IO.Path.GetFileName(file.FileName);
try
{
file.SaveAs(location);
}
catch (Exception ex)
{
location = ex.Message;
}
}
else
{
location = null;
}
return location;
}
}
This question already has an answer here:
Upload and download a file to/from FTP server in C#/.NET
(1 answer)
Closed 4 years ago.
The code below works when i upload files around 12kb and below but for some reason anything above that size results in the program freezing and getting an error:
"The underlying connection was closed: An unexpected error occurred on a receive"
Is there something I am doing wrong?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Net;
namespace FTP3
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void uploadFile(string filePath)
{
FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create("ftp://175.137.158.136" + "/" + Path.GetFileName(filePath));
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential(username, password);
request.UsePassive = true;
request.UseBinary = true;
request.KeepAlive = false;
FileStream stream = File.OpenRead(filePath);
byte[] buffer = new byte[stream.Length];
stream.Read(buffer, 0, buffer.Length);
stream.Close();
Stream reqStream = request.GetRequestStream();
reqStream.Write(buffer, 0, buffer.Length);
reqStream.Close();
MessageBox.Show("Upload complete!");
}
private void button1_Click(object sender, EventArgs e)
{
uploadFile(#"C:\Users\User\Desktop\test\data.xlsx");
}
}
}
you should upload the file in 'chunks', not completely. So please try the following:
using (FileStream fileStream = File.OpenRead(filePath))
{
using (Stream reqStream = request.GetRequestStream())
{
long curFileStreamPos = 0;
long chunkSize = 512;
while (curFileStreamPos < fileStream.Length)
{
if (fileStream.Length - curFileStreamPos < chunkSize)
chunkSize = fileStream.Length - curFileStreamPos;
byte[] buff = new byte[chunkSize];
fileStream.Read(buff, 0, buff.Length);
reqStream.Write(buff, 0, buff.Length);
curFileStreamPos += chunkSize;
}
reqStream.Close();
}
fileStream.Close();
}
I have not tested this snippet, so please verify indexes especially.
If you upload a file at once it may happen that the tcp/ip stack does get timeouts due to preparing the data to upload.
Further, this way you do not create big memory objects when you upload files with hundreds of mb (which would end up completely in memory at your solution)
I'm using ServiceStack to create a Service. In one of the methods I write some data in response's output stream like this: await response.OutputStream.WriteAsync(Consts.DATA, 0, Consts.DATA.Length); where data is a byte[]. Ok, now the problem is when using this service from a client and GET the HttpResponseMessage for the specified method, I don't know how to get the data out. I wan't to unit test that the actual response contains the data I passed when writing to output content.
(I've tried to ReadAsByteArray but it throws an exception. When reading as Stream or String I don't know how to make it a byte[] to compare it in the test with the excpected Consts.DATA byte array.)
I'm pretty new to the field, excuse my ignorance if i miss something. Any help is appreciated.
Thanks!
If you want to use the typed client, you can do (from the documentation):
As raw bytes:
byte[] responseBytes = client.Get<byte[]>("/poco/World");
var dto = responseBytes.FromUtf8Bytes().FromJson<PocoResponse>();
dto.Result //Hello, World
Or as a Stream:
using (Stream responseStream = client.Get<Stream>("/poco/World")) {
var dto = responseStream.ReadFully()
.FromUtf8Bytes()
.FromJson<PocoResponse>();
dto.Result //Hello, World
}
Or even access the populated HttpWebResponse object:
HttpWebResponse webResponse = client.Get<HttpWebResponse>("/poco/World");
webResponse.Headers["X-Response"] //World
using (var stream = webResponse.GetResponseStream())
using (var sr = new StreamReader(stream)) {
var dto = sr.ReadToEnd().FromJson<PocoResponse>();
dto.Result //Hello, World
}
You can also use untyped ServiceStack client to access raw response, it is described in the documentation with samples.
If all you need is load the data from an URL as a Stream and youre using a HttpClient you can just do this to get a stream back:
var result = await client.GetStreamAsync(URL);
I think you can also use GetResponseStream() on your HttpWebResponse.
var result = message.GetResponseStream();
Run your output stream through this static method:
public static byte[] ReadFullStream(Stream st)
{
var lockTaken = false;
try
{
Monitor.Enter(_lock, ref lockTaken);
var size = 0;
var continueRead = true;
var buffer = (byte[])Array.CreateInstance(typeof(byte), 0x10000);
using (MemoryStream ms = new MemoryStream())
{
while (continueRead)
{
size = st.Read(buffer, 0, buffer.Length);
if (size > 0)
{
ms.Write(buffer, 0, size);
}
else
{
continueRead = false;
}
}
return ms.ToArray();
}
}
finally
{
if (lockTaken) { Monitor.Exit(_lock); }
}
}
EDIT: forgot, you'll need this defined at class scope:
private static readonly object _lock = new object();
Read response stream as follow-
using (var reader = new System.IO.StreamReader(response.GetResponseStream()))
{
responseContent = reader.ReadToEnd();
if (response.StatusCode == HttpStatusCode.OK && response.StatusDescription.ToUpper() == "OK" && !string.IsNullOrEmpty(responseContent))
{
objFSLstGetAgent = JsonConvert.DeserializeObject<YourObjectClass>(responseContent);
}
}
I'm trying on c# to download a zip file from a webservice and extract an entry in the memory but when I try to read the stream how is in the documentation of the dotnetzip I get the exception "This stream does not support seek operations” in the "ZipFile.Read(stream)" part.
Somebody could tell me what I'm doing wrong? Thanks in advance
urlAuthentication="https://someurl/?login=foo&token=faa"
var request = (HttpWebRequest)WebRequest.Create(urlAuthentication);
request.Proxy = WebRequest.DefaultWebProxy;
request.Credentials = System.Net.CredentialCache.DefaultCredentials; ;
request.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
using (var ms = new MemoryStream())
{
using (var response = (HttpWebResponse)request.GetResponse())
{
using (var stream =response.GetResponseStream())
{
using (ZipFile zipout = ZipFile.Read(stream))
{
ZipEntry entry = zipout["file1.xml"];
entry.Extract(ms);
}
}
}
}
Apparently dotnetzip requires a stream to support seek operations and the response stream of a HttpWebResponse does not support seeking.
You can solve this issue by first downloading the entire file in memory, and then accessing it:
using (var ms = new MemoryStream())
{
using (MemoryStream seekable = new MemoryStream())
{
using (var stream = response.GetResponseStream())
{
int bytes;
byte[] buffer = new byte[1024];
while ((bytes = stream.Read(buffer, 0, buffer.Length)) > 0)
{
seekable.Write(buffer, 0, bytes);
}
}
seekable.Position = 0;
using (ZipFile zipout = ZipFile.Read(seekable))
{
ZipEntry entry = zipout["file1.xml"];
entry.Extract(ms);
}
}
// access ms
}
I'm a newb, feel free talk down to me.
Sorry to be so vague; the code executes and writes a corrupt file. I can't get into the corrupt file to observe any errors/anomolies. The size does look like a sum of the files being merged.
I've googled the snot outta this and can't find anything I can understand how to implement.
The Word error on open is:
The file cannot be open because there are problems with the contents
and
Word found unreadable content, do you want to continue?
When I click Yes I get the first error again & then I'm out.
THe documents have content controls with the same name, but I've modded this to only add 1 doc in an effort to see if dupe content types would be a problem; same corrupt file results.
btw....my ultimate intent is to overwrite the "template" (...Aggregate Report.dotx) in place. But I can't get a valid file saved ANYWHERE, so...... :-/
using System;
using System.IO;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Linq;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using Word = DocumentFormat.OpenXml.Wordprocessing;
namespace BobsDocMerger.VisualWebPart1
{
[ToolboxItemAttribute(false)]
public class VisualWebPart1 : WebPart
{
// Visual Studio might automatically update this path when you change the Visual Web Part project item.
private const string _ascxPath = #"~/_CONTROLTEMPLATES/BobsDocMerger/VisualWebPart1/VisualWebPart1UserControl.ascx";
protected override void CreateChildControls()
{
System.Web.UI.Control control = this.Page.LoadControl(_ascxPath);
Controls.Add(control);
base.CreateChildControls();
Button btnSubmit = new Button();
btnSubmit.Text = "Assemble Documents";
btnSubmit.Click += new EventHandler(btnSubmit_Click);
Controls.Add(btnSubmit);
}
void btnSubmit_Click(object sender, EventArgs e)
{
SPFolder folder = SPContext.Current.ListItem.Folder;
char[] splitter = { '/' };
string[] folderName = folder.Name.Split(splitter);
string filePrefix = #"Weekly/" + folderName[0] + "/" + folderName[0];
SPFile template = folder.Files[filePrefix + " - Aggregate Report.dotx"];
SPFile file;
byte[] byteArray = template.OpenBinary();
using (MemoryStream mem = new MemoryStream())
{
mem.Write(byteArray, 0, (int)byteArray.Length);
using (WordprocessingDocument myDoc = WordprocessingDocument.Open(mem, true))
{
MainDocumentPart mainPart = myDoc.MainDocumentPart;
//Loop thru content controls
foreach (Word.SdtElement sdt in mainPart.Document.Descendants<Word.SdtElement>().ToList())
{
Word.SdtAlias alias = sdt.Descendants<Word.SdtAlias>().FirstOrDefault();
if (alias != null)
{
//The 2 tags in the Report are AggregateHeader and AggregateBody
string sdtTitle = alias.Val.Value;
string sdtTag = sdt.GetFirstChild<SdtProperties>().GetFirstChild<Tag>().Val;
if (sdtTitle == "Merge")
{
for (int i = 0; i < folder.Files.Count; i++)
{
file = folder.Files[i];
//Do all files that are NOT the Aggregate Report
if (file.Name.IndexOf("Aggregate Report") == -1)
{
if (i == folder.Files.Count-1)
{
AddAltChunk(mainPart, sdt, file, true);
}
else
{
AddAltChunk(mainPart, sdt, file, false);
}
}
}
}
}
}
HttpResponse resp = HttpContext.Current.Response;
resp.ClearContent();
resp.ClearHeaders();
resp.AddHeader("Content-Disposition", "attachment; filename=Assembled Document.docx");
//resp.ContentEncoding = System.Text.Encoding.UTF8;
resp.ContentType = "application/msword";
resp.OutputStream.Write(mem.ToArray(), 0, (int)mem.Length);
resp.Flush();
resp.Close();
HttpContext.Current.ApplicationInstance.CompleteRequest();
}
}
}
protected int id = 1;
void AddAltChunk(MainDocumentPart mainPart, Word.SdtElement sdt, SPFile filename,bool LastPass)
{
string altChunkId = "AltChunkId" + id;
id++;
byte[] byteArray = filename.OpenBinary();
AlternativeFormatImportPart chunk = mainPart.AddAlternativeFormatImportPart(
AlternativeFormatImportPartType.WordprocessingML, altChunkId);
using (MemoryStream mem = new MemoryStream())
{
mem.Write(byteArray, 0, (int)byteArray.Length);
mem.Seek(0, SeekOrigin.Begin);
chunk.FeedData(mem);
}
Word.AltChunk altChunk = new Word.AltChunk();
altChunk.Id = altChunkId;
//Replace content control with altChunk information
DocumentFormat.OpenXml.OpenXmlElement parent = sdt.Parent;
parent.InsertBefore(altChunk, sdt);
if (LastPass) { sdt.Remove(); }
}
}
}
It looks like you're not calling .Seek() properly on the main memory stream, also you seem to be using that single memory stream for both input and output possibly at the same time. (Maybe it's correct, but it's just very confusing to me when it's mixed mode)
I'm assuming you can't access raw filenames and the filesystem:
using(Stream t = template.OpenBinaryStream())
{
using (WordprocessingDocument myDoc = WordprocessingDocument.Open(t, true))
{
using (XmlWriter writer = XmlWriter.Create(resp.OutputStream))
{
// TODO re-add merge logic here once it works
HttpResponse resp = HttpContext.Current.Response;
resp.ClearContent();
resp.ClearHeaders();
resp.AddHeader("Content-Disposition",
"attachment; filename=Assembled Document.docx");
//resp.ContentEncoding = System.Text.Encoding.UTF8;
resp.ContentType = "application/msword";
// resp.OutputStream.Write(mem.ToArray(), 0, (int)mem.Length);
/* new */ myDoc.MainDocumentPart.Document.WriteTo(writer);
resp.Flush();
resp.Close();
HttpContext.Current.ApplicationInstance.CompleteRequest();
}
}
}
PS - I recommend getting a raw template to output correctly first. Then make one tiny change and see that output before re-adding your merge logic.