Click here to Skip to main content
15,886,518 members
Articles / Programming Languages / C#

Convert MP3, MPEG, AVI to Windows Media Formats

Rate me:
Please Sign up or sign in to vote.
4.34/5 (27 votes)
30 May 2005CPOL8 min read 382.7K   11.8K   113  
Video conversion has never been this simple. Use the new Windows Media Encoder to convert different video and audio formats to stream Microsoft audio video standard formats like WMV and WMA.
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using WMEncoderLib;
using WMPREVIEWLib;
using System.IO;

namespace ConvertImagesToMovie
{
	/// <summary>
	/// Summary description for Form1.
	/// </summary>
	public class Form1 : System.Windows.Forms.Form
	{
	
		public static string profileName = Environment.CurrentDirectory + "\\imageencoder4.wme";
		public static string picture_source1 =Environment.CurrentDirectory + "\\clock_02.jpg";
		public static string movie_dest	 = Environment.CurrentDirectory +"\\dest.avi";
		WMEncoder glbEncoder = new WMEncoder();
		IWMEncSourceGroupCollection SrcGrpColl=null;
		private System.Windows.Forms.Timer timer1;
		private System.ComponentModel.IContainer components;

		public Form1()
		{
			//
			// Required for Windows Form Designer support
			//
			InitializeComponent();

			//
			// TODO: Add any constructor code after InitializeComponent call
			//
		}

		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		protected override void Dispose( bool disposing )
		{
			if( disposing )
			{
				if (components != null) 
				{
					components.Dispose();
				}
			}
			base.Dispose( disposing );
		}

		#region Windows Form Designer generated code
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			this.components = new System.ComponentModel.Container();
			this.timer1 = new System.Windows.Forms.Timer(this.components);
			// 
			// timer1
			// 
			this.timer1.Interval = 1000;
			this.timer1.Tick += new System.EventHandler(this.timer1_Tick);
			// 
			// Form1
			// 
			this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
			this.ClientSize = new System.Drawing.Size(292, 266);
			this.Enabled = false;
			this.Name = "Form1";
			this.Opacity = 0;
			this.Text = "Form1";
			this.Load += new System.EventHandler(this.Form1_Load);

		}
		#endregion

		/// <summary>
		/// The main entry point for the application.
		/// </summary>
		[STAThread]
		static void Main(string[] args)
		{
			if ( args.Length >0 && !"".Equals(args[0]) )
				picture_source1 =args[0];
			if (args.Length >1 && !"".Equals(args[1]) )
			{
				movie_dest=args[1];
			}

			Application.Run(new Form1());
		}

		private void Form1_Load(object sender, System.EventArgs e)
		{
			this.Visible = false;
			EncodeFromConsole();
			this.Visible = false;
			
		}
		private FileInfo [] getFiles (string sourceImageName)
		{
			FileInfo file = new FileInfo(sourceImageName);
			string initialStr =  file.Name.Substring(0, file.Name.LastIndexOf("_"));
			
			System.IO.DirectoryInfo dir = file.Directory; 
			System.IO.FileInfo [] f  = dir.GetFiles(initialStr+"*"+file.Extension );
			
		return f;
		}
		/// <summary>
		/// DOESNOT WORK 
		/// </summary>
		/// <returns></returns>
		public IWMEncProfile getProfile1()
		{
			WMEncProfile2 Pro = new WMEncProfile2();
			try 
			{
				Pro.LoadFromFile(@"C:\Program Files\Windows Media Components\Encoder\Profiles\scmeda.prx");
			} 
			catch (Exception ex) 
			{
				Console.Error.WriteLine ( ex.Message);
				return null;
			}
			return Pro;
		}
		/// <summary>
		/// DOESNOT WORK 
		/// </summary>
		/// <returns></returns>
		public IWMEncProfile getProfile ()
		{
			IWMEncProfileCollection ProColl; 
			IWMEncProfile Pro=null; 
			int i; 
			long lLength; 
			ProColl = glbEncoder.ProfileCollection; 
			lLength = ProColl.Count; 
			for (i = 0; i <= lLength - 1; i++) 
			{ 
				Pro = ProColl.Item(i); 
				if (Pro.Name == "Multiple bit rates video (CBR)") 
				{ 
					break; 
				} 
			} 
			//IWMEncBroadcast broadcast = glbEncoder.Broadcast;
			//broadcast.set_PortNumber(WMENC_BROADCAST_PROTOCOL.WMENC_PROTOCOL_HTTP,9091);
			return Pro;
		}


		/// <summary>
		///		The below method/imageencoder4.wme and idea has been taken from a post in microsoft.public.windowsmedia.encoder group "Create WMV files from images (JPG)"
		///		
		/// 	Although this is published in a public forum and is therefore open source, 
		/// 	I would like due attribution to be retained in any derivative works using or adapting this code -  
		/// 	please retain this message in your source files, thanks (p) Neil Smith / WM Digital Media MVP 2005
		///
		/// 	Thanks to Rehan Ahmad and Dean Rowe for the suggestion to use a broadcast profile to counter the 
		/// 	non-encoding of image sequences. This overcomes a limitation in the encoder, 
		/// 	which won't encode any images unless the profile is set to broadcast as well as file archive
		/// </summary>
		/// <returns></returns>
	
		public IWMEncProfile getProfileByTrick()
		{
			
			glbEncoder.Load(profileName);
				
			IWMEncSourceGroup SourceItem=SrcGrpColl.Item(0);
			IWMEncProfile SourceProfile=SourceItem.get_Profile();
			SrcGrpColl.Remove(SourceItem);

			return SourceProfile;
		}
		private bool sEncodeFile(string sourceImageName,string destinationFileName)
		{
			try
			{
				FileInfo [] files  = getFiles(sourceImageName);

				totalFiles = files.Length;
				IWMEncProfile SourceProfile=null;
				SrcGrpColl=glbEncoder.SourceGroupCollection;
				//SourceProfile = getProfile();
				SourceProfile = getProfileByTrick();
				//SourceProfile = getProfile1();
				

				string previousId = "";
				IWMEncSourceGroup2 SrcGrp=null;
				for (int i=0; i<files.Length; i++) 
				{
					SrcGrp=(IWMEncSourceGroup2)SrcGrpColl.Add("ImageFileSource_"+i);
					previousId = "ImageFileSource_"+i;
					SrcGrp.set_Profile(SourceProfile);
					//SrcGrp.SetAutoRollover ( -1,previousId);
					IWMEncVideoSource2 SrcVid=(IWMEncVideoSource2)SrcGrp.AddSource(WMENC_SOURCE_TYPE.WMENC_VIDEO);
					SrcVid.SetInput(files[i].FullName,"","" );
				}
				glbEncoder.File.LocalFileName=destinationFileName;
				

				try 
				{
					glbEncoder.PrepareToEncode(true);
				} 
				catch (Exception ex) 
				{
					Console.Error.WriteLine ( ex.Message);
					return false;
				}
				try 
				{
					timer1.Start();
					finished=false;
					glbEncoder.Start();
					Console.WriteLine  ("Started making File ");
				} 
				catch (Exception ex) 
				{
					Console.Error.WriteLine ( ex.Message);
					return false;
				}
				return true;
			}
			catch(Exception ex){
				Console.Error.WriteLine ( ex.Message);
			}
			return false;
		}


		public void EncodeFromConsole()
		{
			bool boolEncodeStart = sEncodeFile(picture_source1,movie_dest );
			while (!finished)	
			{
				Application.DoEvents();
			}
			Console.WriteLine  ("Finished making File ");
			Application.Exit ();
		}
		int currentFileProcessed=0;
		int totalFiles=0;
		private void timer1_Tick(object sender, System.EventArgs e)
		{

			//	window.status="Processing : "+currentFileProcessed;
			
			if (currentFileProcessed < totalFiles) 
			{
					if(SrcGrpColl.Item(currentFileProcessed)!=null)
					{
							IWMEncSourceGroup selectedSource=SrcGrpColl.Item(currentFileProcessed);
						if (selectedSource.Name.StartsWith("ImageFileSource") )
						{
							glbEncoder.SourceGroupCollection.Active = selectedSource;
						}
					}
							
			} 
			else 
			{
				stopEncoder();
			}
			currentFileProcessed++;	
		}

		bool finished=true;
		private void stopEncoder() 
		{
			glbEncoder.Stop();
			timer1.Stop();
			finished=true;
			
		}
		
	}

	
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect
Pakistan Pakistan
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions