惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

酷 壳 – CoolShell
酷 壳 – CoolShell
H
Hacker News: Front Page
P
Palo Alto Networks Blog
T
ThreatConnect
Apple Machine Learning Research
Apple Machine Learning Research
博客园_首页
T
True Tiger Recordings
P
Privacy & Cybersecurity Law Blog
B
Blog
IT之家
IT之家
Last Week in AI
Last Week in AI
F
Full Disclosure
Hacker News: Ask HN
Hacker News: Ask HN
C
Comments on: Blog
Microsoft Azure Blog
Microsoft Azure Blog
C
Cybersecurity and Infrastructure Security Agency CISA
Microsoft Security Blog
Microsoft Security Blog
博客园 - 【当耐特】
N
News and Events Feed by Topic
NISL@THU
NISL@THU
腾讯CDC
雷峰网
雷峰网
Security Latest
Security Latest
李成银的技术随笔
M
Microsoft Research Blog - Microsoft Research
L
LangChain Blog
L
Lohrmann on Cybersecurity
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
C
Check Point Blog
Y
Y Combinator Blog
Recent Announcements
Recent Announcements
博客园 - Franky
N
News | PayPal Newsroom
V
V2EX
A
About on SuperTechFans
The Register - Security
The Register - Security
月光博客
月光博客
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Google Online Security Blog
Google Online Security Blog
MyScale Blog
MyScale Blog
Cisco Talos Blog
Cisco Talos Blog
Vercel News
Vercel News
WordPress大学
WordPress大学
C
Cyber Attacks, Cyber Crime and Cyber Security
The Hacker News
The Hacker News
IntelliJ IDEA : IntelliJ IDEA – the Leading IDE for Professional Development in Java and Kotlin | The JetBrains Blog
IntelliJ IDEA : IntelliJ IDEA – the Leading IDE for Professional Development in Java and Kotlin | The JetBrains Blog
爱范儿
爱范儿
A
Arctic Wolf
L
LINUX DO - 最新话题
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More

博客园 - 蔡秋心

Windows Azure VM的两种shut down 方式 PowerShell: 找到一个目录下最新的文件 PowerShell: 如何解决File **.ps1 cannot be loaded because the execution of scripts is disabled on this system. Please see "get- help about_sig" for more de 在localhost上使用fiddler 在SQL Server Business Intelligence Development Studio中编辑Dynamcis CRM中的Report Report Design: Best Practices and Guidelines Visual Studio使用小技巧6 – 为代码加上Using(Resolve using)和管理Using(Organize using) Visual Studio使用小技巧5 – 区块选择(box selection)的拷贝(copy)和粘贴(paste) Visual Studio使用小技巧4 – Where am I(在Solution Explorer中显示当前文档) Visual Studio使用小技巧3 – 标签分组(Tab Group)和分割窗口(Split window) Visual Studio使用小技巧2 – 使用任务列表(task list) - 补充 Visual Studio使用小技巧2 – 使用任务列表(task list) Visual Studio使用小技巧1 – HTML编辑器中的格式化 部署Dotnetnuke Site到虚拟目录和端口不为80的网站 asp.net使用COM组件需要的权限设置 前台线程(Foreground Threads)和后台线程(Background Threads) 在Dynamics CRM 的 Entity Form中显示记录的ID的方法 如何使用VS2005创建web安装包 使用Visual Studio中的Item Template
转贴: A Simple c# Wrapper for ffMpeg
蔡秋心 · 2014-01-10 · via 博客园 - 蔡秋心

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.IO;

using System.Diagnostics;

using System.Configuration;

using System.Text.RegularExpressions;

namespace ffMpeg

{

    public class Converter

    {

        #region Properties

        private string _ffExe;

        public string ffExe

        {

            get

            {

                return _ffExe;

            }

            set

            {

                _ffExe = value;

            }

        }

        private string _WorkingPath;

        public string WorkingPath

        {

            get

            {

                return _WorkingPath;

            }

            set

            {

                _WorkingPath = value;

            }

        }

        #endregion

        #region Constructors

        public Converter()

        {

            Initialize();

        }

        public Converter(string ffmpegExePath)

        {

            _ffExe = ffmpegExePath;

            Initialize();

        }

        #endregion

        #region Initialization

        private void Initialize()

        {

            if (string.IsNullOrEmpty(_ffExe))

            {

                object o = ConfigurationManager.AppSettings["ffmpeg:ExeLocation"];

                if (o == null)

                {

                    throw new Exception("Could not find the location of the ffmpeg exe file.  The path for ffmpeg.exe " +

                    "can be passed in via a constructor of the ffmpeg class (this class) or by setting in the app.config or web.config file.  " +

                    "in the appsettings section, the correct property name is: ffmpeg:ExeLocation");

                }

                else

                {

                    if (string.IsNullOrEmpty(o.ToString()))

                    {

                        throw new Exception("No value was found in the app setting for ffmpeg:ExeLocation");

                    }

                    _ffExe = o.ToString();

                }

            }

            string workingpath = GetWorkingFile();

            if (string.IsNullOrEmpty(workingpath))

            {

                throw new Exception("Could not find a copy of ffmpeg.exe");

            }

            _ffExe = workingpath;

            if (string.IsNullOrEmpty(_WorkingPath))

            {

                object o = ConfigurationManager.AppSettings["ffmpeg:WorkingPath"];

                if (o != null)

                {

                    _WorkingPath = o.ToString();

                }

                else

                {

                    _WorkingPath = string.Empty;

                }

            }

        }

        private string GetWorkingFile()

        {

            if (File.Exists(_ffExe))

            {

                return _ffExe;

            }

            if (File.Exists(Path.GetFileName(_ffExe)))

            {

                return Path.GetFileName(_ffExe);

            }

            return null;

        }

        #endregion

        #region Get the File without creating a file lock

        public static System.Drawing.Image LoadImageFromFile(string fileName)

        {

            System.Drawing.Image theImage = null;

            using (FileStream fileStream = new FileStream(fileName, FileMode.Open,

            FileAccess.Read))

            {

                byte[] img;

                img = new byte[fileStream.Length];

                fileStream.Read(img, 0, img.Length);

                fileStream.Close();

                theImage = System.Drawing.Image.FromStream(new MemoryStream(img));

                img = null;

            }

            GC.Collect();

            return theImage;

        }

        public static MemoryStream LoadMemoryStreamFromFile(string fileName)

        {

            MemoryStream ms = null;

            using (FileStream fileStream = new FileStream(fileName, FileMode.Open,

            FileAccess.Read))

            {

                byte[] fil;

                fil = new byte[fileStream.Length];

                fileStream.Read(fil, 0, fil.Length);

                fileStream.Close();

                ms = new MemoryStream(fil);

            }

            GC.Collect();

            return ms;

        }

        #endregion

        #region Run the process

        private string RunProcess(string Parameters)

        {

            ProcessStartInfo oInfo = new ProcessStartInfo(this._ffExe, Parameters);

            oInfo.UseShellExecute = false;

            oInfo.CreateNoWindow = true;

            oInfo.RedirectStandardOutput = true;

            oInfo.RedirectStandardError = true;

            string output = null; StreamReader srOutput = null;

            try

            {

                Process proc = System.Diagnostics.Process.Start(oInfo);

                proc.WaitForExit();

                srOutput = proc.StandardError;

                output = srOutput.ReadToEnd();

                proc.Close();

            }

            catch (Exception)

            {

                output = string.Empty;

            }

            finally

            {

                if (srOutput != null)

                {

                    srOutput.Close();

                    srOutput.Dispose();

                }

            }

            return output;

        }

        #endregion

        #region GetVideoInfo

        public VideoFile GetVideoInfo(MemoryStream inputFile, string Filename)

        {

            string tempfile = Path.Combine(this.WorkingPath, System.Guid.NewGuid().ToString() + Path.GetExtension(Filename));

            FileStream fs = File.Create(tempfile);

            inputFile.WriteTo(fs);

            fs.Flush();

            fs.Close();

            GC.Collect();

            VideoFile vf = null;

            try

            {

                vf = new VideoFile(tempfile);

            }

            catch (Exception ex)

            {

                throw ex;

            }

            GetVideoInfo(vf);

            try

            {

                File.Delete(tempfile);

            }

            catch (Exception)

            {

            }

            return vf;

        }

        public VideoFile GetVideoInfo(string inputPath)

        {

            VideoFile vf = null;

            try

            {

                vf = new VideoFile(inputPath);

            }

            catch (Exception ex)

            {

                throw ex;

            }

            GetVideoInfo(vf);

            return vf;

        }

        public void GetVideoInfo(VideoFile input)

        {

            string Params = string.Format("-i {0}", input.Path);

            string output = RunProcess(Params);

            input.RawInfo = output;

            Regex re = new Regex("[D|d]uration:.((\\d|:|\\.)*)");

            Match m = re.Match(input.RawInfo);

            if (m.Success)

            {

                string duration = m.Groups[1].Value;

                string[] timepieces = duration.Split(new char[] { ':', '.' });

                if (timepieces.Length == 4)

                {

                    input.Duration = new TimeSpan(0, Convert.ToInt16(timepieces[0]), Convert.ToInt16(timepieces[1]), Convert.ToInt16(timepieces[2]), Convert.ToInt16(timepieces[3]));

                }

            }

            re = new Regex("[B|b]itrate:.((\\d|:)*)");

            m = re.Match(input.RawInfo);

            double kb = 0.0;

            if (m.Success)

            {

                Double.TryParse(m.Groups[1].Value, out kb);

            }

            input.BitRate = kb;

            re = new Regex("[A|a]udio:.*");

            m = re.Match(input.RawInfo);

            if (m.Success)

            {

                input.AudioFormat = m.Value;

            }

            re = new Regex("[V|v]ideo:.*");

            m = re.Match(input.RawInfo);

            if (m.Success)

            {

                input.VideoFormat = m.Value;

            }

            re = new Regex("(\\d{2,3})x(\\d{2,3})");

            m = re.Match(input.RawInfo);

            if (m.Success)

            {

                int width = 0; int height = 0;

                int.TryParse(m.Groups[1].Value, out width);

                int.TryParse(m.Groups[2].Value, out height);

                input.Width = width;

                input.Height = height;

            }

            input.infoGathered = true;

        }

        #endregion

        #region Convert to FLV

        public OutputPackage ConvertToFLV(MemoryStream inputFile, string Filename)

        {

            string tempfile = Path.Combine(this.WorkingPath, System.Guid.NewGuid().ToString() + Path.GetExtension(Filename));

            FileStream fs = File.Create(tempfile);

            inputFile.WriteTo(fs);

            fs.Flush();

            fs.Close();

            GC.Collect();

            VideoFile vf = null;

            try

            {

                vf = new VideoFile(tempfile);

            }

            catch (Exception ex)

            {

                throw ex;

            }

            OutputPackage oo = ConvertToFLV(vf);

            try{

                File.Delete(tempfile);

            } catch(Exception) {

            }

            return oo;

        }

        public OutputPackage ConvertToFLV(string inputPath)

        {

            VideoFile vf = null;

            try

            {

                vf = new VideoFile(inputPath);

            }

            catch (Exception ex)

            {

                throw ex;

            }

            OutputPackage oo = ConvertToFLV(vf);

            return oo;

        }

        public OutputPackage ConvertToFLV(VideoFile input)

        {

            if (!input.infoGathered)

            {

                GetVideoInfo(input);

            }

            OutputPackage ou = new OutputPackage();

            string filename = System.Guid.NewGuid().ToString() + ".jpg";

            int secs;

            secs = (int)Math.Round(TimeSpan.FromTicks(input.Duration.Ticks / 3).TotalSeconds, 0);

            string finalpath = Path.Combine(this.WorkingPath, filename);

            string Params = string.Format("-i {0} {1} -vcodec mjpeg -ss {2} -vframes 1 -an -f rawvideo", input.Path, finalpath, secs);

            string output = RunProcess(Params);

            ou.RawOutput = output;

            if (File.Exists(finalpath))

            {

                ou.PreviewImage = LoadImageFromFile(finalpath);

                try

                {

                    File.Delete(finalpath);

                }

                catch (Exception) { }

            } else {

                Params = string.Format("-i {0} {1} -vcodec mjpeg -ss {2} -vframes 1 -an -f rawvideo", input.Path, finalpath, 1);

                output = RunProcess(Params);

                ou.RawOutput = output;

                if (File.Exists(finalpath)) {

                    ou.PreviewImage = LoadImageFromFile(finalpath);

                    try

                    {

                        File.Delete(finalpath);

                    }

                    catch (Exception) { }

                }

            }

            finalpath = Path.Combine(this.WorkingPath, filename);

            filename = System.Guid.NewGuid().ToString() + ".flv";

            Params = string.Format("-i {0} -y -ar 22050 -ab 64 -f flv {1}", input.Path, finalpath);

            output = RunProcess(Params);

            if (File.Exists(finalpath))

            {

                ou.VideoStream = LoadMemoryStreamFromFile(finalpath);

                try

                {

                    File.Delete(finalpath);

                }

                catch (Exception) { }

            }

            return ou;

        }

        #endregion

    }

    public class VideoFile

    {

        #region Properties

        private string _Path;

        public string Path

        {

            get

            {

                return _Path;

            }

            set

            {

                _Path = value;

            }

        }

        public TimeSpan Duration { get; set; }

        public double BitRate { get; set; }

        public string AudioFormat { get; set; }

        public string VideoFormat { get; set; }

        public int Height { get; set; }

        public int Width { get; set; }

        public string RawInfo { get; set; }

        public bool infoGathered {get; set;}

        #endregion

        #region Constructors

        public VideoFile(string path)

        {

            _Path = path;

            Initialize();

        }

        #endregion

        #region Initialization

        private void Initialize()

        {

            this.infoGathered = false;

            if (string.IsNullOrEmpty(_Path))

            {

                throw new Exception("Could not find the location of the video file");

            }

            if (!File.Exists(_Path))

            {

                throw new Exception("The video file " + _Path + " does not exist.");

            }

        }

        #endregion

    }

    public class OutputPackage

    {

        public MemoryStream VideoStream { get; set; }

        public System.Drawing.Image PreviewImage { get; set; }

        public string RawOutput { get; set; }

        public bool Success { get; set; }

    }

}