微信下载录音文件

版权声明:本文为博主原创文章,需要转载尽管转载。 https://blog.csdn.net/z5976749/article/details/86145770
        /// <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
            { }
        }

猜你喜欢

转载自blog.csdn.net/z5976749/article/details/86145770