5,692,513 members and growing! (16,891 online)
Email Password   helpLost your password?
Languages » C# » How To     Intermediate License: The Code Project Open License (CPOL)

Convert MP3 to EXE

By Giorgi Dalakishvili

An article showing how to convert MP3 file to executable file
C# (C# 1.0, C# 2.0, C# 3.0, C#), Windows (Windows, WinXP), .NET (.NET, .NET 2.0)VS2005, Visual Studio, Dev

Posted: 19 May 2007
Updated: 18 Mar 2008
Views: 66,219
Bookmarked: 142 times
Announcements
Loading...



Search    
Advanced Search
Sitemap
85 votes for this Article.
Popularity: 7.60 Rating: 3.94 out of 5
12 votes, 14.1%
1
2 votes, 2.4%
2
4 votes, 4.7%
3
14 votes, 16.5%
4
53 votes, 62.4%
5
Sample Image - maximum width is 600 pixels

Contents

Introduction

In this article, you will learn how to convert an MP3 file to an executable file.

What You Will Learn From This Article

  1. How to compile C# code during runtime
  2. How to play an MP3 file using C#
  3. How to insert a file into your application as an embedded resource and extract embedded resource dynamically during runtime
  4. How to implement dragging files from Explorer
  5. How to insert a file into your application as an embedded resource through designer.

Conversion

Here is a description how this program works.

First the user chooses the MP3 files he wished to convert to EXE. After that, an instance of CompilerParameters class is created and the specified MP3 file is added as an embedded resource through the EmbeddedResources property of CompilerParameters class. This is done in a worker thread using BackGroundWorker component. The icon of the executable file can be chosen by the user and command line option is used to specify it.

The source code we compile is source code of a simple application that doesn't have a window, extracts the embedded MP3 file and plays that file. The source file that is compiled is itself embedded in the first application and extracted to temp folder at startup.

Implementation Details

Compiling Source File Dynamically

Microsoft.CSharp.CSharpCodeProvider pr
                                 = new Microsoft.CSharp.CSharpCodeProvider();
CompilerParameters cp = new CompilerParameters();
string pathtoicon="";       // pathtoicon variable holds the path of the icon 
                           // for generated executable
if (File.Exists(Application.StartupPath + "\\icon.ico"))
{ 
    pathtoicon= Application.StartupPath + "\\icon.ico";
}

if (skinRadioButton2.Checked)
{ 
    pathtoicon = this.pictureBox1.ImageLocation;
}

cp.CompilerOptions = "/target:winexe" + " " + "/win32icon:" + "\"" + 
                         pathtoicon + "\"";    // specify options for compiler
cp.GenerateExecutable = true;                  // yes, generate an EXE file
cp.IncludeDebugInformation = false;            // here we add the mp3 file as 
                                               // as an embedded resource
cp.EmbeddedResources.Add(this.textBox1.Text);  // were to save the executable 
                                               // specified by savefiledialog
cp.OutputAssembly = sv.FileName;

cp.GenerateInMemory = false;
cp.ReferencedAssemblies.Add("System.dll");         // this and the following 
cp.ReferencedAssemblies.Add("System.Data.dll");    // lines add references
cp.ReferencedAssemblies.Add("System.Deployment.dll");
cp.ReferencedAssemblies.Add("System.Drawing.dll");
cp.ReferencedAssemblies.Add("System.Windows.Forms.dll");
cp.ReferencedAssemblies.Add("System.Xml.dll");
cp.TreatWarningsAsErrors = false;

string temp = Environment.GetEnvironmentVariable("TEMP");
 
// compile the source file
CompilerResults cr = pr.CompileAssemblyFromFile(cp,  temp + "\\it.cs"); 
if (cr.Errors.Count>0)
{ 
    MessageBox.Show("There was an error while converting the file","Error",
                 MessageBoxButtons.OK,MessageBoxIcon.Error);   //error checking
}

Extracting Embedded File During Runtime

This portion of code is from the source file that is compiled by the program. This code extracts embedded resource from the application during runtime.

//this code requires System.Reflection namespace

//get names of resources in the assembly
string[] myassembly
     = Assembly.GetExecutingAssembly().GetManifestResourceNames();

//create stream from the resource. 
Stream theResource 
   = Assembly.GetExecutingAssembly().GetManifestResourceStream(myassembly[0]);
 
//Create binary reader from the stream

BinaryReader br = new BinaryReader(theResource);  
//then filestream
FileStream fs = new FileStream(Environment.GetEnvironmentVariable("TEMP") +
                                +"\\it.mp3" , FileMode.Create); 
BinaryWriter bw = new BinaryWriter(fs);    //and then binary writer
byte[] bt = new byte[theResource.Length];  //read the resource
theResource.Read(bt,0, bt.Length);         //and then write to the file
bw.Write(bt);                              //don't forget to close all streams
br.Close();
bw.Close();

We pass myassambly[0] to GetManifestResourceStream because there is only one resource.

Drag and Drop

To implement drag and drop functionality from Windows Explorer, I use the class that came with the source code of this book.

You need to create an instance of the DragAndDropFileComponent class and set up event handler. Here is the code snippet:

DragAndDropFileComponent drag = new DragAndDropFileComponent(this.components);
drag.BeginInit();
drag.FileDropped += new FileDroppedEventHandler(drag_FileDropped);
drag.HostingForm = this;
drag.EndInit();

Here is the event handler:

 void drag_FileDropped(object sender, FileDroppedEventArgs e)
 { 
    if (e.Filenames!=null & 
    e.Filenames.Length!=0 & e.Filenames[0].EndsWith(".mp3"))
 {
   this.textBox1.Text = e.Filenames[0];
 }
 }

Playing MP3 File

In order to play an MP3 file from my application, I used this class. After you add MP3Player to your project, playing MP3 files is very simple. Here is the code snippet from the source file that is compiled:

MP3Player pl = new MP3Player();
try
   {
    pl.Open(Environment.GetEnvironmentVariable("TEMP") + "\\it.mp3");
    pl.Play();
    //wait until the file is played and then quit
    //this no longer causes 100% CPU utilization
    System.Threading.Thread.Sleep(((int)pl.AudioLength)+1);
    Application.Exit();
    }
    catch (Exception ex)
    { }   

The program starts playing the MP3 file when it is loaded and quits when playing is over.

Final Thoughts

The idea itself of converting an MP3 file to an EXE file is a little bit strange and the whole application is interesting.

History

  • 18th May, 2007 - Initial version
  • 26th May, 2007 - Fixed the bug that was causing 100% CPU load when launching the generated EXE

License

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

About the Author

Giorgi Dalakishvili


Mvp

Occupation: Software Developer
Location: Georgia Georgia

Other popular C# articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 25 of 49 (Total in Forum: 49) (Refresh)FirstPrevNext
GeneralSmall errormemberFrits8815:30 28 Sep '08  
GeneralRe: Small errormvpGiorgi Dalakishvili21:19 28 Sep '08  
GeneralRe: Small errormemberFrits8812:22 29 Sep '08  
NewsError downloading source codememberSteve Povah4:23 4 May '08  
GeneralRe: Error downloading source codemvpGiorgi Dalakishvili5:24 4 May '08  
GeneralA very interesting idea!memberTonyTonyQ18:49 24 Mar '08  
GeneralRe: A very interesting idea!mvpGiorgi Dalakishvili23:20 24 Mar '08  
Generalyou read good booksmember crysler 13:16 20 Feb '08  
GeneralRe: you read good booksmvpGiorgi Dalakishvili21:26 20 Feb '08  
Joke"ქართველი ხარ, ბიჭო"?memberLOTEBI17:16 11 Feb '08  
Questionneed to edit mp3 filememberMember 9416971:59 24 Jan '08  
GeneralWhat is the purpose of mp3 to exe converter?memberMember 456478723:10 7 Jan '08  
GeneralRe: What is the purpose of mp3 to exe converter?mvpGiorgi Dalakishvili0:57 8 Jan '08  
GeneralHistorymemberArmando Airo'3:52 14 Nov '07  
GeneralRe: HistorymemberJim Weiler12:49 15 Nov '07  
GeneralThreadStateExceptionmemberGreg Cadmes13:10 21 Aug '07  
GeneralRe: ThreadStateExceptionmemberGiorgi Dalakishvili0:18 22 Aug '07  
GeneralWhy?memberMichael Sync23:57 13 Aug '07  
GeneralRe: Why?memberGiorgi Dalakishvili23:59 13 Aug '07  
GeneralRe: Why?memberMichael Sync6:24 15 Aug '07  
GeneralRe: Why?memberGiorgi Dalakishvili6:39 15 Aug '07  
GeneralRe: Why?memberMichael Sync17:58 15 Aug '07  
Generalgood article,memberJuraj Borza21:40 6 Aug '07  
GeneralRe: good article,memberGiorgi Dalakishvili1:00 7 Aug '07  
Generalnice concept!memberThatsAlok20:46 5 Aug '07  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 18 Mar 2008
Editor: Deeksha Shenoy
Copyright 2007 by Giorgi Dalakishvili
Everything else Copyright © CodeProject, 1999-2008
Web15 | Advertise on the Code Project