c# asp.net获取音频时长及音频转码

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/huwei2003/article/details/78369134

c# asp.net获取音频时长及音频转码

直接上代码并见注释

	/// <summary>
        /// 利用ShellClass获取音频文件时长; 
	/// 如果添加引用编译提示"不能引用嵌入式接口之类的错误",把引用属性里的嵌入式***,设为false;
	/// asp.net 环境下测试未通过,c#未测试;
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <returns></returns>
        private int GetDurationByShellClass(string filePath)
        {
            try
            {
                ShellClass sh = new ShellClass();
                Folder dir = sh.NameSpace(Path.GetDirectoryName(filePath));
                FolderItem item = dir.ParseName(Path.GetFileName(filePath));
                string str = dir.GetDetailsOf(item, 27); // 获取歌曲时长。
                if (str != "")
                {
                    var matchs = Regex.Match(str, @"(\d{2}):(\d{2}):(\d{2})");
                    var hour = Convert.ToInt32(matchs.Groups[1].Value);
                    var minute = Convert.ToInt32(matchs.Groups[2].Value);
                    var second = Convert.ToInt32(matchs.Groups[3].Value);

                    var len = hour * 3600 + minute * 60 + second;
                    return len;
                }
                else
                {
                    return 0;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            return 0;
        }
	/// <summary>
        /// 利用WMPLib获取音频文件时长;
	/// 如果添加引用编译提示"不能引用嵌入式接口之类的错误",把引用属性里的嵌入式***,设为false;
	/// asp.net 环境下测试未通过,c#未测试;
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        private int GetDurationByWMPLib(string filePath)
        {
            try
            {
                WMPLib.WindowsMediaPlayerClass player = new WMPLib.WindowsMediaPlayerClass();
                player.URL = filePath;
                var duration = Math.Ceiling(player.duration);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            return 0;
        }
		
	/// <summary>
        /// 利用MediaInfoDotNet获取音频文件时长
	/// 如果添加引用编译提示"不能引用嵌入式接口之类的错误",把引用属性里的嵌入式***,设为false;
	/// asp.net 环境下测试未通过,c#测试通过;
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        private int GetDurationByMediaInfoDotNet(string filePath)
        {
            try
            {
                MediaInfoDotNet.MediaFile aviFile = new MediaInfoDotNet.MediaFile(filePath);
                if (aviFile.Audio.Count > 0)
                {
                    var duration = aviFile.General.Duration;
                    return duration;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            return 0;
        }

        [DllImport("Kernel32", CharSet = CharSet.Auto)]
        static extern Int32 GetShortPathName(String path, StringBuilder shortPath, Int32 shortPathLength);
        [DllImport("winmm.dll")]
        public static extern int mciSendString(string m_strCmd, StringBuilder m_strReceive, int m_v1, int m_v2);
        public static string MusicTime(string musicFilePath)//musicFilePath是歌曲文件地址
        {
            if (File.Exists(musicFilePath))//是否存在这个文件
            {
                //利用MCI命令,返回值为文件时间
                StringBuilder shortpath = new StringBuilder(80);
                GetShortPathName(musicFilePath, shortpath, shortpath.Capacity);
                string musicname = shortpath.ToString();
                StringBuilder buf = new StringBuilder(80);
                mciSendString("close all", buf, buf.Capacity, 0);
                mciSendString("open " + musicname + " alias media", buf, buf.Capacity, 0);
                mciSendString("status media length", buf, buf.Capacity, 0);
                //return buf.ToString().Trim();
                double ms = Convert.ToDouble(buf.ToString().Trim());
                TimeSpan ts = new TimeSpan(0, 0, 0, 0, (int)ms);
                return ts.ToString().Substring(3, 5);//这里你自己去决定返回的是什么格式
            }
            return "0";//如果文件不存在就返回"0"
        }
		
	/// <summary>
        /// 利用ffmpeg获取指定文件的时长,单位:秒;
        /// 调用:var duration = GetDurationByffmpeg(filePath, @"/ffmpeg.exe");
        /// </summary>
        /// <param name="fileName">文件路径</param>
        /// <param name="ffmpegVirtualPath">ffmpeg.exe的虚拟路径</param>
        /// <returns></returns>
        public static int GetDurationByffmpeg(string fileName, string ffmpegVirtualPath)
        {
            int duration = 0;
            try
            {
                if (!File.Exists(fileName))
                {
                    return 0;
                }
                using (System.Diagnostics.Process pro = new System.Diagnostics.Process())
                {
                    pro.StartInfo.UseShellExecute = false;
                    pro.StartInfo.ErrorDialog = false;
                    pro.StartInfo.RedirectStandardError = true;

                    pro.StartInfo.FileName = System.Web.HttpContext.Current.Server.MapPath(ffmpegVirtualPath);
                    // AppDomain.CurrentDomain.BaseDirectory +"ffmpeg.exe";
                    pro.StartInfo.Arguments = " -i " + fileName;

                    pro.Start();
                    System.IO.StreamReader errorreader = pro.StandardError;
                    pro.WaitForExit(1 * 1000);

                    string result = errorreader.ReadToEnd();
                    if (!string.IsNullOrEmpty(result))
                    {
                        result = result.Substring(result.IndexOf("Duration: ") + ("Duration: ").Length,
                            ("00:00:00").Length);

                        var matchs = Regex.Match(result, @"(\d{2}):(\d{2}):(\d{2})");
                        var hour = Convert.ToInt32(matchs.Groups[1].Value);
                        var minute = Convert.ToInt32(matchs.Groups[2].Value);
                        var second = Convert.ToInt32(matchs.Groups[3].Value);

                        var len = hour * 3600 + minute * 60 + second;
                        duration = len;
                    }
                    return duration;
                }
            }
            catch (Exception ex)
            {
                log.Error(ex);
            }
            return 0;
        }
        /// <summary>
        /// 利用ffmpeg进行转码; 如 amr转mp3
        /// </summary>
        /// <param name="inputFile">输入文件,要转码的文件</param>
        /// <param name="outputFile">转码后的文件</param>
        /// <param name="ffmpegVirtualPath">ffmpeg.exe的虚拟路径</param>
        /// <returns></returns>
        public static bool FromffmpegTurnCode(string inputFile, string outputFile, string ffmpegVirtualPath)
        {
            try
            {
                if (!File.Exists(inputFile))
                {
                    return false;
                }
                using (System.Diagnostics.Process pro = new System.Diagnostics.Process())
                {
                    pro.StartInfo.UseShellExecute = false;
                    pro.StartInfo.ErrorDialog = false;
                    pro.StartInfo.RedirectStandardError = true;

                    pro.StartInfo.FileName = System.Web.HttpContext.Current.Server.MapPath(ffmpegVirtualPath);
                    // AppDomain.CurrentDomain.BaseDirectory +"ffmpeg.exe";
                    pro.StartInfo.Arguments = " -i " + inputFile + " -y " + outputFile;

                    pro.Start();
                    System.IO.StreamReader errorreader = pro.StandardError;
                    pro.WaitForExit(30 * 1000);
                    return true;
                }
            }
            catch (Exception ex)
            {
                log.Error(ex);
            }
            return false;
        }

--- end ---

展开阅读全文

没有更多推荐了,返回首页