Similar to this client, the first box is to input the path of compressed video, you can select multiple, the second box is to output the path of compressed video, you can select only one, the third box is the progress bar, and the last box is to click compress now
First restrict the file format, allowing only video formats to be selected
private void create_video_list()
{
video_list.Add(".MP4");
video_list.Add(".mp4");
video_list.Add(".MOV");
video_list.Add(".mov");
video_list.Add(".AVI");
video_list.Add(".avi");
video_list.Add(".MPEG");
video_list.Add(".mpeg");
video_list.Add(".WMV");
video_list.Add(".wmv");
video_list.Add(".3GP");
video_list.Add(".3gp"); } Use video_list.Contains(path.getextension (Path)) to determine if it is a video format20Files under M are not allowed to be selected through the functionpublic static long FileSize(string filePath)// Determine the file size
{
// Define a FileInfo object that is associated with the file pointed to by filePath to get its size
FileInfo fileInfo = new FileInfo(filePath);
returnfileInfo.Length; } to determine the size of the file and then drag the file to join the file pathprivate void Form1_DragEnter(object sender, DragEventArgs e)// Drag and drop to add file
{
string allIntputPath = "";
// Get drag and drop data
if (e.Data.GetDataPresent(DataFormats.FileDrop))
{
string[] content = (string[])e.Data.GetData(DataFormats.FileDrop);
for (int i = 0; i < content.Length; i++)
{
// This is the full path
if (is_videos(content[i].ToString())) {
allIntputPath = content[i].ToString() + "\r\n";
inputList.Add(content[i].ToString() + "\r\n"); } } changeText(allIntputPath); Select the compressed file path by clicking the buttonprivate void SelectFolder_Click(object sender, EventArgs e)// Select the video path
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.Multiselect = true;// This value determines whether multiple files can be selected
dialog.Title = "Please select folder";
dialog.Filter = "All files (*. *) | *. *";
if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string allIntputPath = "";
string[] strNames = dialog.FileNames;
for (int i = 0; i < strNames.Length; i++)
{
if (is_videos(strNames[i].ToString()))
{
allIntputPath = strNames[i].ToString() + "\r\n";
inputList.Add(strNames[i].ToString() + "\r\n"); } } changeText(allIntputPath); }} Threads are then used to perform compression, Thread t =new Thread(ZipVideos);
t.IsBackground = true;// Set the foreground thread to the background thread, which will be terminated with the application without waiting for the thread to terminate.
t.Start();
public void ZipVideos()
{
successCount = 0;
if (isVideoIsEmpty)
{
string[] striparr = this.skinTextBox1.Text.Split(new string[] { "\r\n" }, StringSplitOptions.None);
foreach (String ph in striparr)
{
if (ph.Length > 1)
{
zippath = System.IO.Path.GetFileName(ph);
try
{
this.SelectFolder.Enabled = false;
this.SaveFolderPath.Enabled = false;
this.MakeVideo.Enabled = false;
ConvertVideo(ph);
}
catch (System.Exception ex)
{
LogHelper.WriteLog(ex.ToString());
}
}
Thread.Sleep(1000); }}} and then throughpublic void ConvertVideo(String inputpath)// Compress the video
{
now_path = inputpath;
isVideoIsEmpty = false;
string filename = System.IO.Path.GetFileName(inputpath);
string outputpath = VideoOutPath + "\\zip" + filename;
string sPath = Environment.GetEnvironmentVariable("ffmpeg");
string new_fps = "25";
string ffmpegpath = @"ffmpeg.exe";
LogHelper.WriteLog(ffmpegpath);
altime=GetVideoDuration(ffmpegpath, inputpath);
int intbitr = 0;
int.TryParse(allbitrate, out intbitr);
string bitcount = (intbitr / 3).ToString() + "k";
LogHelper.WriteLog(altime+"@"+bitcount + "@" + allbitrate);
string cmd1 = "";
if (new_resolution.Length < 1)
{
cmd1 = "-i " + inputpath + " -r " + new_fps + " -threads 2" + " -y " + outputpath + "";
}
if (allbitrate.Length < 1)
{
cmd1 = "-i " + inputpath + " -r " + new_fps + " -threads 2" + " -y " + outputpath + "";
}
if (allbitrate.Length > 2 && new_resolution.Length > 2)
{
cmd1 = "-i " + inputpath + " -b " + bitcount + " -s " + new_resolution + " -r " + new_fps + " -threads 2" + " -y " + outputpath + "";
}
LogHelper.WriteLog("@ -- -- -- -- -- -- -- -- -- -- -- -- -- -- --");
LogHelper.WriteLog(cmd1);
LogHelper.WriteLog("@ -- -- -- -- -- -- -- -- -- -- -- -- -- -- --");
Process p = new Process();// Create an external calling thread
p.StartInfo.FileName = ffmpegpath;// The absolute path to call the external program
p.StartInfo.Arguments = cmd1;// Parameter (here is FFMPEG parameter)
p.StartInfo.UseShellExecute = false;// Start thread without OS shell (must be FALSE, see MSDN for details)
p.StartInfo.RedirectStandardError = true;// write the StandardError output to the StandardError stream. It took me over 2 months to learn... Mencoder is captured using standardOutput.)
p.StartInfo.CreateNoWindow = true;// Do not create a process window
p.ErrorDataReceived += new DataReceivedEventHandler(Output);// An event generated when an external program (in this case FFMPEG) outputs a stream. In this case, the stream processing is transferred to the following method
p.Start();// Start the thread
p.BeginErrorReadLine();// Start asynchronous reading
p.WaitForExit();// Block waiting for the process to finish
p.Close();// Close the process
p.Dispose();// Release resources} to compress videoCopy the code
The whole code is as follows
using CCWin;
using log4net;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace CompaessVideo
{
public partial class ZipVideo : CCSkinMain
{
public ZipVideo()
{
InitializeComponent();
}
readonly static object _locker = new object(a);string VideoInutPath = "";
string VideoOutPath = "";
string new_resolution = "";
string allbitrate = "";
Boolean isVideoIsEmpty = true;
Queue<string> videoQueue = new Queue<string> ();string zippath = "";
int successCount = 0;
ArrayList inputList = new ArrayList();
ArrayList video_list = new ArrayList();
int altime = 0;
string now_path = "";
private void ZipVideo_Load(object sender, EventArgs e)// The initialization function of the incoming project
{
LogHelper.WriteLog("Log");
this.AllowDrop = true;
this.skinTextBox1.SkinTxt.Leave += skinLabel1Change;
create_video_list();
}
private void skinLabel1Change(object sender, EventArgs e) {// Enter the path in the reinput box
inputList.Clear();
string[] striparr = this.skinTextBox1.Text.Split(new string[] { "\r\n" }, StringSplitOptions.None);
System.Text.RegularExpressions.Regex regex =new System.Text.RegularExpressions.Regex(@"^[a-zA-Z]:((\\+[^\/:*?""<>|]+)+)\s*$");
foreach (String ph in striparr)
{
if (System.IO.File.Exists(ph)) {
if (is_videos(ph))
{
inputList.Add(ph + "\r\n"); }}}}private void create_video_list()
{
video_list.Add(".MP4");
video_list.Add(".mp4");
video_list.Add(".MOV");
video_list.Add(".mov");
video_list.Add(".AVI");
video_list.Add(".avi");
video_list.Add(".MPEG");
video_list.Add(".mpeg");
video_list.Add(".WMV");
video_list.Add(".wmv");
video_list.Add(".3GP");
video_list.Add(".3gp");
}
private Boolean is_videos(string filePath) { // Check whether it is a video file and whether it is larger than 20m
string path = filePath.Replace("\r\n"."");
long filesize = FileSize(filePath);
long sizem=filesize / 1048576;
if (path.Length > 1)
{
//Path.GetExtension(filePath).ToString()
if (video_list.Contains(Path.GetExtension(path)))
{
if (sizem > 20)
{
return true;
}
else {
MessageBox.Show("Do not add videos smaller than 20M");
return false; }}else
{
MessageBox.Show("Do not add non-video files");
return false; }}else
{
return false; }}public static long FileSize(string filePath)// Determine the file size
{
// Define a FileInfo object that is associated with the file pointed to by filePath to get its size
FileInfo fileInfo = new FileInfo(filePath);
return fileInfo.Length;
}
private void Form1_DragEnter(object sender, DragEventArgs e)// Drag and drop to add file
{
string allIntputPath = "";
// Get drag and drop data
if (e.Data.GetDataPresent(DataFormats.FileDrop))
{
string[] content = (string[])e.Data.GetData(DataFormats.FileDrop);
for (int i = 0; i < content.Length; i++)
{
// This is the full path
if (is_videos(content[i].ToString())) {
allIntputPath = content[i].ToString() + "\r\n";
inputList.Add(content[i].ToString() + "\r\n"); } } changeText(allIntputPath); }}private void changeText(String inputDictory)// Put the file name in the box
{
if (inputDictory.Length > 1) {
this.skinTextBox1.Text = "";
if (!this.skinTextBox2.Text.Contains("\ \"))
{
string folder = System.IO.Path.GetDirectoryName(inputDictory.Replace("\r\n".""));
VideoOutPath = @folder;
this.skinTextBox2.Text = VideoOutPath;
}
if (inputList.Count > 0)
{
foreach (String pt in inputList)
{
this.skinTextBox1.Text += pt; }}}}private void SelectFolder_Click(object sender, EventArgs e)// Select the video path
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.Multiselect = true;// This value determines whether multiple files can be selected
dialog.Title = "Please select folder";
dialog.Filter = "All files (*. *) | *. *";
if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string allIntputPath = "";
string[] strNames = dialog.FileNames;
for (int i = 0; i < strNames.Length; i++)
{
if (is_videos(strNames[i].ToString()))
{
allIntputPath = strNames[i].ToString() + "\r\n";
inputList.Add(strNames[i].ToString() + "\r\n"); } } changeText(allIntputPath); }}private void SaveFolderPath_Click(object sender, EventArgs e)// Select the path to store the video
{
this.skinTextBox2.Text = "";
string[] paths = new string[0];
if (String.IsNullOrEmpty(this.skinTextBox1.Text))
{
MessageBox.Show("Please select the path to get the video");
return;
}
paths = VideoInutPath.Split('\ \');
string temp = paths[paths.Length - 1];
System.Windows.Forms.FolderBrowserDialog dialog = new System.Windows.Forms.FolderBrowserDialog();
dialog.Description = "Please select the folder where Txt resides";
if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
if (string.IsNullOrEmpty(dialog.SelectedPath))
{
MessageBox.Show(this."Folder path cannot be empty"."Tip");
return;
}
else
{
string filename = dialog.SelectedPath;
string folder = System.IO.Path.GetFullPath(dialog.SelectedPath);
VideoOutPath = @folder;
this.skinTextBox2.Text = VideoOutPath; }}}private void MakeVideo_Click(object sender, EventArgs e)// Click compress video
{
CheckForIllegalCrossThreadCalls = false;
string[] striparr = this.skinTextBox1.Text.Split(new string[] { "\r\n" }, StringSplitOptions.None);
foreach (String ph in striparr)
{
if (ph.Length > 1) {
if(! System.IO.File.Exists(ph)) { MessageBox.Show("File format is incorrect");
return; }}}if (String.IsNullOrEmpty(this.skinTextBox1.Text))
{
MessageBox.Show("Please select the path to get the video");
return;
}
if (String.IsNullOrEmpty(this.skinTextBox2.Text))
{
MessageBox.Show("Please select a path to save the video.");
return;
}
try
{
Thread t = new Thread(ZipVideos);
t.IsBackground = true;// Set the foreground thread to the background thread, which will be terminated with the application without waiting for the thread to terminate.
t.Start();
this.SelectFolder.Enabled = false;
this.skinTextBox1.Enabled = false;
this.skinTextBox2.Enabled = false;
this.SaveFolderPath.Enabled = false;
this.MakeVideo.Enabled = false; } catch (System.Exception ex) { LogHelper.WriteLog(ex.ToString()); }}public void ZipVideos()
{
successCount = 0;
if (isVideoIsEmpty)
{
string[] striparr = this.skinTextBox1.Text.Split(new string[] { "\r\n" }, StringSplitOptions.None);
foreach (String ph in striparr)
{
if (ph.Length > 1)
{
zippath = System.IO.Path.GetFileName(ph);
try
{
this.SelectFolder.Enabled = false;
this.SaveFolderPath.Enabled = false;
this.MakeVideo.Enabled = false;
ConvertVideo(ph);
}
catch (System.Exception ex)
{
LogHelper.WriteLog(ex.ToString());
}
}
Thread.Sleep(1000); }}}public void ZipVideos1()
{
successCount = 0;
string[] striparr = this.skinTextBox1.Text.Split(new string[] { "\r\n" }, StringSplitOptions.None);
foreach (String ph in striparr)
{
if (ph.Length > 1) { videoQueue.Enqueue(ph); }}while (true)
{
if(videoQueue.Count ! =0)
{
if (isVideoIsEmpty)
{
lock (_locker)
{
String path1 = "";
String path2 = "";
try
{
path1 = videoQueue.Dequeue();
}
catch
{
path1 = "";
}
try
{
path2 = videoQueue.Dequeue();
}
catch
{
path2 = "";
}
String zippath1 = System.IO.Path.GetFileName(path1);
String zippath2 = System.IO.Path.GetFileName(path2);
zippath = zippath1 + "/" + zippath2;
try
{
this.SelectFolder.Enabled = false;
this.SaveFolderPath.Enabled = false;
this.MakeVideo.Enabled = false;
if (path1.Length > 1)
{
Task task1 = new Task(() =>
{
ConvertVideo(path1);
});
task1.Start();
}
if (path2.Length > 1)
{
Task task2 = newTask(() => { ConvertVideo(path2); }); task2.Start(); } } catch (System.Exception ex) { LogHelper.WriteLog(ex.ToString()); }}}}else
{
break;
}
Thread.Sleep(1000); }}public void ConvertVideo(String inputpath)// Compress the video
{
now_path = inputpath;
isVideoIsEmpty = false;
string filename = System.IO.Path.GetFileName(inputpath);
string outputpath = VideoOutPath + "\\zip" + filename;
string sPath = Environment.GetEnvironmentVariable("ffmpeg");
string new_fps = "25";
string ffmpegpath = @"ffmpeg.exe";
LogHelper.WriteLog(ffmpegpath);
altime=GetVideoDuration(ffmpegpath, inputpath);
int intbitr = 0;
int.TryParse(allbitrate, out intbitr);
string bitcount = (intbitr / 3).ToString() + "k";
LogHelper.WriteLog(altime+"@"+bitcount + "@" + allbitrate);
string cmd1 = "";
if (new_resolution.Length < 1)
{
cmd1 = "-i " + inputpath + " -r " + new_fps + " -threads 2" + " -y " + outputpath + "";
}
if (allbitrate.Length < 1)
{
cmd1 = "-i " + inputpath + " -r " + new_fps + " -threads 2" + " -y " + outputpath + "";
}
if (allbitrate.Length > 2 && new_resolution.Length > 2)
{
cmd1 = "-i " + inputpath + " -b " + bitcount + " -s " + new_resolution + " -r " + new_fps + " -threads 2" + " -y " + outputpath + "";
}
LogHelper.WriteLog("@ -- -- -- -- -- -- -- -- -- -- -- -- -- -- --");
LogHelper.WriteLog(cmd1);
LogHelper.WriteLog("@ -- -- -- -- -- -- -- -- -- -- -- -- -- -- --");
Process p = new Process();// Create an external calling thread
p.StartInfo.FileName = ffmpegpath;// The absolute path to call the external program
p.StartInfo.Arguments = cmd1;// Parameter (here is FFMPEG parameter)
p.StartInfo.UseShellExecute = false;// Start thread without OS shell (must be FALSE, see MSDN for details)
p.StartInfo.RedirectStandardError = true;// write the StandardError output to the StandardError stream. It took me over 2 months to learn... Mencoder is captured using standardOutput.)
p.StartInfo.CreateNoWindow = true;// Do not create a process window
p.ErrorDataReceived += new DataReceivedEventHandler(Output);// An event generated when an external program (in this case FFMPEG) outputs a stream. In this case, the stream processing is transferred to the following method
p.Start();// Start the thread
p.BeginErrorReadLine();// Start asynchronous reading
p.WaitForExit();// Block waiting for the process to finish
p.Close();// Close the process
p.Dispose();// Release resources
}
private int GetVideoDuration(string ffmpegfile, string sourceFile)// Get video details
{
try
{
using (System.Diagnostics.Process ffmpeg = new System.Diagnostics.Process())
{
String duration; // soon will hold our video's duration in the form "HH:MM:SS.UU"
String result; // temp variable holding a string representation of our video's duration
StreamReader errorreader; // StringWriter to hold output from ffmpeg
ffmpeg.StartInfo.UseShellExecute = false;
ffmpeg.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
ffmpeg.StartInfo.RedirectStandardError = true;
ffmpeg.StartInfo.FileName = ffmpegfile;
ffmpeg.StartInfo.Arguments = "-i " + sourceFile;
ffmpeg.Start();
errorreader = ffmpeg.StandardError;
ffmpeg.WaitForExit();
result = errorreader.ReadToEnd();
LogHelper.WriteLog("-- -- -- -- -- -- -- -- -- -- -- -- -- -- --");
LogHelper.WriteLog(result);
LogHelper.WriteLog("-- -- -- -- -- -- -- -- -- -- -- -- -- -- --");
duration = result.Substring(result.IndexOf("Duration: ") + ("Duration: ").Length, ("00:00:00").Length);
string allsizes = result.Substring(result.IndexOf("Video: ") + ("Video: ").Length);
LogHelper.WriteLog(allsizes);
LogHelper.WriteLog(allsizes.Split(', ') [0]);
string new_fps = allsizes.Split(', ') [4].Split(new string[] { "fps" }, StringSplitOptions.None)[0];
string sizes = allsizes.Split(', ') [2].Split('[') [0];
new_resolution = sizes;
string[] birts = result.Substring(result.IndexOf("bitrate: ") + ("bitrate: ").Length).Split(new string[] { "Stream" }, StringSplitOptions.None);
allbitrate = birts[0].ToString().Split(new string[] { "kb" }, StringSplitOptions.None)[0];
string[] ss = duration.Split(':');
int h = int.Parse(ss[0]);
int m = int.Parse(ss[1]);
int s = int.Parse(ss[2]);
return h * 3600 + m * 60 + s;
}
}
catch (System.Exception ex)
{
LogHelper.WriteLog(ex.ToString());
return 60; }}private void Output(object sendProcess, DataReceivedEventArgs output)// Prints details about the video generation process
{
if(! String.IsNullOrEmpty(output.Data)) { createFileTime(output);if (output.Data.Contains("headers"))
{
successCount += 1;
isVideoIsEmpty = true;
}
if (output.Data.Contains("No such file"))
{
this.SelectFolder.Enabled = true;
this.SaveFolderPath.Enabled = true;
this.MakeVideo.Enabled = true;
this.skinTextBox1.Text = "";
this.skinTextBox2.Text = "";
MessageBox.Show("Cannot find this file, please change path");
}
if (inputList.Count == successCount)
{
this.skinTextBox1.Enabled = true;
this.skinTextBox2.Enabled = true;
this.skinTextBox1.Text = "";
this.skinTextBox2.Text = "";
this.SelectFolder.Enabled = true;
this.SaveFolderPath.Enabled = true;
this.MakeVideo.Enabled = true;
now_path = "All documents";
inputList.Clear();
MessageBox.Show("All compressed."); }}}private void createFileTime(DataReceivedEventArgs output) {
LogHelper.WriteLog("Log content" + output.Data);
string outputData = output.Data;
string[] filetimes = outputData.Split(' ');
foreach (string filetime in filetimes) {
if (filetime.Contains("time=")) {
string[] fl_time = filetime.Split('=');
try
{
float tm = 0;
float.TryParse(fl_time[1].out tm);
int program =Convert.ToInt32(((tm/altime)*100));
this.skinLabel1.Text = now_path+"Compress progress:";
skinProgressBar1.Value = program;
}
catch(Exception e){
LogHelper.WriteLog(e.ToString());
}
}
}
}
}
}
Copy the code