微信下載錄音檔案
阿新 • • 發佈:2019-01-09
/// <SUMMARY> /// 下載儲存多媒體檔案,返回多媒體儲存路徑 /// </SUMMARY> /// <PARAM name="ACCESS_TOKEN"></PARAM> /// <PARAM name="MEDIA_ID"></PARAM> /// <RETURNS></RETURNS> public string GetMultimedia(HttpContext context) { //下面都是為了獲取微信token,我是存在xml中的。 string filepath = HttpContext.Current.Server.MapPath("/AK.xml"); StreamReader str = new StreamReader(filepath, System.Text.Encoding.UTF8); XmlDocument xml = new XmlDocument(); xml.Load(str); str.Close(); str.Dispose(); var Token = xml.SelectSingleNode("xml").SelectSingleNode("Access_Token").InnerText; string file = string.Empty; string content = string.Empty; string strpath = string.Empty; string savepath = string.Empty; string MEDIA_ID = context.Request["MEDIA_ID"]; //上面都是為了獲取token MEDIA_ID是微信的檔案ID,需要在前臺用wx.uploadVoice上傳 string stUrl = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=" + Token + "&media_id=" + MEDIA_ID; HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(stUrl); req.Method = "GET"; using (WebResponse wr = req.GetResponse()) { HttpWebResponse myResponse = (HttpWebResponse)req.GetResponse(); strpath = myResponse.ResponseUri.ToString(); //WebClient mywebclient = new WebClient(); string basePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "file", "VoiceCard"); HttpCookie mycookie = context.Request.Cookies[CommManage.hd_cookie_name]; string openId = mycookie.Value; var fileName = openId + new Random().Next(1000, 9999); savepath = Path.Combine(basePath , fileName + ".amr"); try { //mywebclient.DownloadFile(strpath, savepath); DownLoad(strpath, savepath, "audio/amr"); ///amr轉換成MP3格式 //mywebclient.DownloadFileCompleted += new AsyncCompletedEventHandler(webClient_DownloadFileCompleted) ; //Thread.Sleep(5000); //把從微信下載的檔案轉成mp3格式,如果要在h5頁面裡聽需要轉換,如果只是簡單下載則不需要轉碼 ConvertToAmr(Path.Combine(basePath, fileName + ".amr"),Path.Combine(basePath, fileName + ".mp3")); //轉換成功後儲存 hd_join_user my_model = main_db.hd_join_user.FirstOrDefault(p => p.open_id == openId && p.hd_code == VoiceCardManage.hd_code); var voice = new hd_articlevote_images(); voice.article_code = my_model.id.ToString(); voice.images = fileName + ".mp3"; voice.hd_code = VoiceCardManage.hd_code; main_db.SaveChanges(); return fileName + ".mp3"; } catch (Exception ex) { savepath = ex.ToString(); Log.Error("bug" , ex.ToString().Substring(0,100)); return ""; } } }
上面是從微信端下載音訊檔案,其他檔案也是類似
//下載檔案 public static bool DownLoad(string url, string path, string contentType) { try { HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url); req.ServicePoint.Expect100Continue = false; req.Method = "GET"; req.KeepAlive = true; req.ContentType = contentType;// "image/png"; using (HttpWebResponse rsp = (HttpWebResponse)req.GetResponse()) { using (Stream reader = rsp.GetResponseStream()) { using (FileStream writer = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write)) { byte[] buff = new byte[512]; int c = 0; //實際讀取的位元組數 while ((c = reader.Read(buff, 0, buff.Length)) > 0) { writer.Write(buff, 0, c); } } } } return true; } catch (Exception e) { return false; } }
amr格式轉成MP3
/// <summary> /// 將amr音訊轉成mp3手機音訊 /// </summary> /// <param name="applicationPath">ffmeg.exe檔案路徑</param> /// <param name="fileName">amr檔案的路徑(帶檔名)</param> /// <param name="targetFilName">生成目前mp3檔案路徑(帶檔名)</param> /// string c 裡面的ffmpeg.exe需要下載這個檔案,路徑是ffmpeg.exe的檔案路勁 public void ConvertToAmr( string fileName, string targetFilName) { string c = @"G:\toolsZ\ffmpeg64\bin" + @"\ffmpeg.exe -i " + fileName + " " + targetFilName; c = c.Replace("//", "\\").Replace("/", "\\"); Log.Info("ff", c); Cmd(c); }
開啟ffmpeg.exe檔案需要開啟cmd.exe
/// <summary>
/// 執行Cmd命令
/// </summary>
private void Cmd(string c)
{
try
{
process = new System.Diagnostics.Process();
process.StartInfo.FileName = "cmd.exe";
process.StartInfo.UseShellExecute = false;
process.StartInfo.CreateNoWindow = true;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardInput = true;
process.Start();
process.StandardInput.WriteLine(c);
process.StandardInput.AutoFlush = true;
process.StandardInput.WriteLine("exit");
StreamReader reader = process.StandardOutput;//擷取輸出流
//process.StandardInput.Flush();
//process.StandardInput.Close();
process.WaitForExit();
}
catch
{ }
}