文章内容

.net mvc 使用ffmpeg.exe在线转换音频文件

  • 2018-12-10 14:13:20
  • 129
  • 0
  • 0

FileResult   

       public FileResult downvoice(string file,string filename)
       {
            file = System.Web.HttpUtility.UrlDecode(file);
            filename = System.Web.HttpUtility.UrlDecode(filename);
            string url = "http://10.76.249.11:8123" + file;
            string mp3SavePth = Server.MapPath("/public/wav/") + filename ;
            FileInfo fi = new FileInfo(mp3SavePth);
            if (fi.Exists)
            {
                return File(mp3SavePth, "application/octet-stream", filename);
            }
            else
            {
                string path = ffmpegHelper.ConvertToMp3(url, mp3SavePth);
                if (!string.IsNullOrEmpty(path))
                {
                    //path = "/public/wav/" + filename;
                    // HttpWebRequest myRequest = (HttpWebRequest)HttpWebRequest.Create(path);// 打开网络连接
                    //Stream readStream = myRequest.GetResponse().GetResponseStream();// 向服务器请求,获得服务器的回应数据流
                    return File(mp3SavePth, "application/octet-stream", filename);
                }
                else
                {
                    return null;
                }
            }
        }



ffmpegHelper


    public class ffmpegHelper
    {
        public static string ConvertToMp3(string pathBefore, string pathLater)
        {
            string c = HttpContext.Current.Server.MapPath("/public/ffmpeg/") + @"ffmpeg.exe -i " + pathBefore + " " + pathLater;
            string str = RunCmd(c);
            return str;
        }
        /// <summary>
        /// 执行Cmd命令
        /// </summary>
        private static string RunCmd(string c)
        {
            try
            {
                ProcessStartInfo info = new ProcessStartInfo("cmd.exe");
                info.RedirectStandardOutput = false;
                info.UseShellExecute = false;
                Process p = Process.Start(info);
                p.StartInfo.UseShellExecute = false;
                p.StartInfo.RedirectStandardInput = true;
                p.StartInfo.RedirectStandardOutput = true;
                p.StartInfo.RedirectStandardError = true;
                p.Start();
                p.StandardInput.WriteLine(c);
                p.StandardInput.AutoFlush = true;
                Thread.Sleep(1000);
                p.StandardInput.WriteLine("exit");
                p.WaitForExit();
                string outStr = p.StandardOutput.ReadToEnd();
                p.Close();
                return outStr;
            }
            catch (Exception ex)
            {
                return "error" + ex.Message;
            }
        }
    }

ffmpeg下载

https://pan.baidu.com/s/1Wjf-vzYTdGcKbm2pwwWVtg   提取码:wu2x