Click here to Skip to main content
15,894,825 members
Articles / Programming Languages / C#

MP3 Helper Class

Rate me:
Please Sign up or sign in to vote.
4.80/5 (9 votes)
23 Jul 2010CPOL2 min read 40.8K   2.8K   34  
An MP3 helper class to help you play MP3 files and embedded resources' streams
using System;
using System.IO;
using System.Runtime.InteropServices;

namespace QSoft
{
    class MP3Helper
    {
        [DllImport("winmm.dll")]
        private static extern long mciSendString(string strCommand, System.Text.StringBuilder strReturn, int iReturnLength, IntPtr hwndCallback);
        
        public static void Play(string MP3_FileName,bool Repeat)
        {
            mciSendString("open \"" + MP3_FileName + "\" type mpegvideo alias MediaFile", null, 0, IntPtr.Zero);
            mciSendString("play MediaFile" + (Repeat ? " repeat" :String.Empty), null, 0, IntPtr.Zero);
        }
        public static void Play(byte[] MP3_EmbeddedResource, bool Repeat)
        {
            extractResource(MP3_EmbeddedResource, Path.GetTempPath() + "resource.tmp");
            mciSendString("open \"" + Path.GetTempPath() + "resource.tmp" + "\" type mpegvideo alias MediaFile", null, 0, IntPtr.Zero);
            mciSendString("play MediaFile" + (Repeat ? " repeat" : String.Empty), null, 0, IntPtr.Zero);
        }

        public static void Pause()
        {
            mciSendString("stop MediaFile", null, 0, IntPtr.Zero);
        }

        public static void Stop()
        {
            mciSendString("close MediaFile", null, 0, IntPtr.Zero);
        }

        private static void extractResource(byte[] res,string filePath)
        {
            FileStream fs;
            BinaryWriter bw;

            if (!File.Exists(filePath))
            {
                fs = new FileStream(filePath, FileMode.OpenOrCreate);
                bw = new BinaryWriter(fs);

                foreach (byte b in res)
                    bw.Write(b);

                bw.Close();
                fs.Close();
            }
        }
    }
}

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
Retired QSoft
Yemen Yemen
Biography?! I'm not dead yet!
www.QSoftOnline.com

Comments and Discussions