Stream stream = File.OpenRead(Server.MapPath("0.jpg")); long len = stream.Length; byte[] buff = new byte[len]; stream.Read(buff, 0, buff.Length); Stream f = new FileStream(Server.MapPath("1.jpg"), FileMode.OpenOrCreate); BinaryWriter write = new BinaryWriter(f); write.Write(buff, 0, buff.Length);
using (Stream responseStream = response.GetResponseStream()) { using (FileStream localFileStream = new FileStream(Server.MapPath(path), FileMode.OpenOrCreate)) { var buffer = new byte[1024]; int bytesRead; while ((bytesRead = responseStream.Read(buffer, 0, buffer.Length)) > 0) { localFileStream.Write(buffer, 0, bytesRead); } } }
下面程式碼,用於把其他網站的wav引起提取存放在本機,然後轉換為pcm格式,然後提交到百度介面,最終把語音轉換為文字。
參考 http://ai.baidu.com/docs#/ASR-API/top 介紹
protected void Button1_Click(object sender, EventArgs e) { string url = "http://localhost:50961/16.wav"; string tempMedia=FetchMedia(url); string pcmFile=ConvertMedia(tempMedia); var data = System.IO.File.ReadAllBytes(Server.MapPath(pcmFile)); Asr _asrClient = new Asr("key", "key"); // { "corpus_no": "6579488890526359184", "err_msg": "success.", "err_no": 0, "result": [ "今天中午吃什麼呢我想吃回鍋肉,不知道你喜歡不喜歡," ], "sn": "87884864331531906633" } string json = _asrClient.Recognize(data, "pcm", 16000).ToString(); BaiduResult r = Newtonsoft.Json.JsonConvert.DeserializeObject<BaiduResult>(json); Response.Write(r.result[0]); try { System.IO.File.Delete(Server.MapPath(tempMedia)); } catch { } try { System.IO.File.Delete(Server.MapPath(pcmFile)); } catch { } } public string FetchMedia(string fullURL) { HttpWebRequest request = WebRequest.Create(fullURL) as HttpWebRequest; string filename = Guid.NewGuid().ToString() + ".wav"; string path = "temp/" + filename; using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) { using (Stream responseStream = response.GetResponseStream()) { using (FileStream localFileStream = new FileStream(Server.MapPath(path), FileMode.OpenOrCreate)) { var buffer = new byte[1024*10]; int bytesRead; while ((bytesRead = responseStream.Read(buffer, 0, buffer.Length)) > 0) { localFileStream.Write(buffer, 0, bytesRead); } } } } return path; } public string ConvertMedia(string mediaName) { string exe = Server.MapPath("ffmpeg.exe"); string fromFile = Server.MapPath(mediaName); string newFilename = "temp/" + Guid.NewGuid().ToString()+".pcm"; string tofile = Server.MapPath(newFilename); //ffmpeg -y -i 16k.wav -acodec pcm_s16le -f s16le -ac 1 -ar 16000 16k.pcm System.Diagnostics.Process p = System.Diagnostics.Process.Start(exe, " -y -i \""+fromFile+"\" -acodec pcm_s16le -f s16le -ac 1 -ar 16000 \""+tofile+"\" "); // p.StartInfo.UseShellExecute = false; p.WaitForExit(); return newFilename; }