Play multimedia files using MCI and C# - Deon Spengler

Play multimedia files using MCI and C#

Published Thursday, July 29, 2004 2:03 AM

Play multimedia files using MCI and C#

 

Multimedia can enhance the graphical user interface and the presentation of your application. It is very important that you application is visual appealing to your user, but while not making your application difficult to work with. You can use a sound file to notify a user of an event, or a video file demonstrating what the user must do next. I have wrapped most of the common MCI multimedia command in a class file. This will make it easier for you to use MCI in your applications.

 

Media Control Interface (MCI)

 

The Media Control Interface (MCI) provides standard commands for playing multimedia devices and recording multimedia resource files. These commands are a generic interface to nearly every kind of multimedia device. MCI provides applications with device-independent capabilities for controlling audio and visual peripherals. Your application can use MCI to control any supported multimedia device, including waveform-audio devices, MIDI sequencers, CD audio devices, and digital-video (video playback) devices.

 

mciSendString

 

The mciSendString function sends a command string to an MCI device. The device that the command is sent to is specified in the command string.

 

Enter the code

 

First we import the “winmm.dll” so that we can use the mciSendString function that we need.

 

[DllImport("winmm.dll")]

private static extern long mciSendString(string strCommand,

StringBuilder strReturn, int iReturnLength, IntPtr hwndCallback);

 

strCommand

 

Pointer to a null-terminated string that specifies an MCI command string.

For a list, see Multimedia Command Strings.

 

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/multimed/htm/_win32_multimedia_command_strings.asp

 

strReturn

 

Pointer to a buffer that receives return information. If no return information is needed, this parameter can be null

.

iReturnLength

 

Size, in characters, of the return buffer specified by the strReturn parameter.

 

hwndCallback

 

Handle to a callback window if the "notify" flag was specified in the command string.

 

The open command

 

The open command initializes a device. All MCI devices recognize this command.

To send this command, call the mciSendString function with the strCommand parameter set as follows.

 

public void Open(string sFileName)

            {

                        //mpegvideo is the device type that we are going to use

        //the format of the song location must be with double quotes around it

                        sCommand = "open \"" + sFileName + "\" type

                        mpegvideo alias MediaFile";

                        mciSendString(sCommand, null, 0, IntPtr.Zero);

            }

 

We are using the mpegvideo device because we can play almost all of the newest media files with it, e.g. divx, xvid, mp3, avi, wav, mpeg, mpg and wmv.

 

The play command

 

The play command starts playing a device. CD audio, digital-video, MIDI sequencer, videodisc, VCR, and waveform-audio devices recognize this command. To send this command, call the mciSendString function with the strCommand parameter set as follows.

 

            public void Play()

            {

                        //tell the device to play

                        sCommand = "play MediaFile";

        mciSendString(sCommand, null, 0, IntPtr.Zero);

            }

 

Conclusion

 

I have only covered the basics in this tutorial; there are a lot more MCI function sitting in the wrapper that I wrote. Download the attached source code and demo application to get an idea of how to use the wrapper. You are all welcome to take the wrapper an improve/change it to suit your needs.

 

Happy coding !!!!

 

Download: Source code

by deon
Filed under:

Comments

# Varun Chatterji said on Tuesday, October 05, 2004 6:10 AM

Excellent!! This is just what I needed. Thanks so much. I am going to use this to create a remote control for PDA. Will give credit of course!

# Andy Johns said on Thursday, October 14, 2004 1:44 AM

Very cool work. Thanks for posting. I'll be borrowing pieces of this ;)
Do you know of a way to play videos that are encoded as a embedded resource?
-Andy

# Stefan Brandt said on Tuesday, October 19, 2004 1:34 PM

Excellent example - was looking for a way to play Mp3 files, and this is it!

Thanks!

/Stefan

# Shodan said on Tuesday, November 02, 2004 7:16 PM

Could someone be so nice and tell me how the hwndCallback Notify just to run a function after a file has been played or recorded? Thanks a lot in C# please.
Here's a little of the code i've written.

Email: Krzysztof@Zdzieblo.com

[DllImport ("winmm.dll")]
private static extern int mciSendString(String s1, StringBuilder s2, int l1, int l2);
[DllImport ("winmm.dll")]
private static extern int mciSendString(string strCommand, StringBuilder strReturn, int iReturnLength, IntPtr hwndCallback);
[DllImport ("winmm.dll")]
private static extern int mciGetErrorString(int l1, StringBuilder s1, int l2);
void MciExecute(String Command, StringBuilder Buffer, int Length) {
int err = mciSendString(Command, Buffer, Length, 0);
if (err != 0) {
int retval = mciGetErrorString(err, Buffer, Length);
WriteStatus("MCI error: "+Buffer.ToString());
}
}
void MciExecute(String Command, StringBuilder Buffer, int Length, IntPtr Callback) {
int err = mciSendString(Command, Buffer, Length, Callback);
if (err != 0) {
int retval = mciGetErrorString(err, Buffer, Length);
WriteStatus("MCI error: "+Buffer.ToString());
}
}


String Filename = "test";
MciExecute("open new type waveaudio alias "+Filename, recordBuffer,1024);
String mciString="set "+Filename+" bitspersample "+ BitsPerSample+" channels "+Channels+" samplespersec "+SamplesPerSec;
MciExecute(mciString, errorBuffer, 128);
MciExecute("record "+Filename+" to 5000 notify",recordBuffer,1024);

# Craig said on Friday, December 10, 2004 12:13 PM

Do you know of a way to play mp3 files that are encoded as an embedded resource ???

# Rami said on Tuesday, December 14, 2004 5:07 PM

I've been using this code and ran into a few problems.
The biggest one is that after running a sequence of movie files using this code, the program crashes and I get the "do you want to report this error" message of microsoft.
Another problem but less crucial is that getting the duration of a file only works for me with wmv files but not with mpeg files.
Any help will be much appreciated?

# William said on Saturday, March 12, 2005 10:17 AM

I am trying to use the mcisendstring to play a divx format video. When I use it in conjunction with the avivideo format, I get disjointed video without audio. When I use the mpegvideo format, the system crashes. Any suggestions

# Saravanan said on Monday, April 18, 2005 11:20 AM

Hi, I have written a small utility to record and play voice files using mciSendString. Play is working ok. But inthe recording, some of the words in the end are getting chopped off. Any idea on this please?

# Jake said on Saturday, April 30, 2005 8:38 PM

Does anyone know how I can automatically close the file after it's done playing??

# casual_coder said on Sunday, May 21, 2006 9:03 AM

While playing avi files using MCI in c#, anly audio plays,video is not displayed.can any 1 help how 2 overcome this

# casual_coder said on Sunday, May 21, 2006 9:04 AM

I am able to play only wmv format using MCI, can any1 tell how 2 play avi & mpeg formats also using MCI in C#

# Zolomon said on Sunday, June 17, 2007 1:15 AM

Aww.. The source is gone, can't download it. :\

Would appreciate if you could upload it again!

# Raj said on Sunday, July 15, 2007 7:25 AM

Hello

This sure is a stupid question :

I get the command string as "open \"music\\Possible.mp3\" type mpegvideo alias MediaFile"

But the mp3 file is not playing....can someone help me get it ???

THANKS A LOT in advance.

Raj

# Cipher said on Saturday, July 28, 2007 9:16 PM

Aww.. The source is gone, can't download it. :\

Would appreciate if you could upload it again!

# Николай said on Sunday, July 29, 2007 10:48 AM

Большое спасибо

# leviettriuit said on Wednesday, December 19, 2007 1:16 PM

thanks. but do you have books application MCI with c#?

can you help me?

thanks.

i need it. hiiiiiiiiiii everyboby

# Hanson said on Wednesday, January 09, 2008 6:27 PM

Thank you Deon.

That's exactly what I need to know.

# P.An said on Friday, February 01, 2008 2:13 PM

A very good article

# Julian said on Sunday, February 17, 2008 1:33 PM

This is a GREAT Article! Just wanted to know how can I broadcast the music file i'm playing to other pc?

# vedi said on Monday, February 18, 2008 10:39 AM

play av files in asp pages

# Randhir said on Tuesday, March 04, 2008 9:30 PM

I use the coding but problem on the iis server Pls help me how to implement the code on the iis server

# vuegdaraps said on Monday, April 14, 2008 2:15 PM

bKvQ8Y  <a href="lmcidnhqwkbk.com/.../a>, [url=http://twcuhccjqhel.com/]twcuhccjqhel[/url], [link=http://seysioxryqez.com/]seysioxryqez[/link], http://rzhmfqzrfesm.com/

# giuhyta said on Sunday, August 24, 2008 3:51 PM

ushN9z  <a href="sxamxzrqgwzy.com/.../a>, [url=http://hypdnhddefmm.com/]hypdnhddefmm[/url], [link=http://acegguwgjrhl.com/]acegguwgjrhl[/link], http://zxijwuisotle.com/

# ehzfhdcs said on Monday, August 25, 2008 3:22 AM

7PU8To  <a href="ixkptgyyxjti.com/.../a>, [url=http://hjkaboqmkltb.com/]hjkaboqmkltb[/url], [link=http://zkdkaahnabkj.com/]zkdkaahnabkj[/link], http://djenabxfivsw.com/

# Manjunath said on Sunday, November 23, 2008 7:20 AM

This code works perfectly fine if it is in a exe (application) but it will not work if it is a dll.

Currently i have a dll which contains the implementaion of the playing audio file. but if i use this dll in another application, I get "266 (error)" meanging.. " unable to load the driver "..

can anybody help me???

regards

Manjunath G

Manjunath.govindaraju@gmail.com

# Andrew said on Wednesday, February 04, 2009 4:05 PM

Hello,

trying to play sound with mciSendString function under WinXP x64

Calling function like this

       [DllImport("winmm.dll", EntryPoint = "mciSendStringW", CharSet = CharSet.Unicode)]

       protected static extern Int32 mciSendString([MarshalAs(UnmanagedType.LPWStr)]   String lpstrCommand,

                                                   [MarshalAs(UnmanagedType.LPWStr)]   StringBuilder lpstrReturnString,

                                                   [MarshalAs(UnmanagedType.U4)]       UInt32 uReturnLength,

                                                   [MarshalAs(UnmanagedType.SysUInt)]  IntPtr hwndCallback );

further trying to open .mp3 file

string Pcommand = "open \"C:some_sound.mp3\" type mpegvideo alias MediaFile";

int Err = mciSendString(Pcommand, null, 128, IntPtr.Zero);

Err ==  MCIERR_INVALID_DEVICE_NAME - The specified device is not open nor recognized by MCI.

Any suggestion?

# rvikxe said on Thursday, February 05, 2009 7:21 PM

tYKyBh  <a href="okajgefccobz.com/.../a>, [url=http://iwvdjyacadao.com/]iwvdjyacadao[/url], [link=http://kjnhluzgshgm.com/]kjnhluzgshgm[/link], http://cumfzwvwmyts.com/

# udghzg said on Wednesday, February 11, 2009 4:21 PM

d8158g  <a href="lrhhqtzjbkdm.com/.../a>, [url=http://tinglfuvxlja.com/]tinglfuvxlja[/url], [link=http://wknblxnftcrq.com/]wknblxnftcrq[/link], http://patwzeahtgqz.com/

# ksqbncp said on Monday, March 16, 2009 4:24 PM

n1lXBB  <a href="rsfwmbicncfo.com/.../a>, [url=http://qhedpyikyydt.com/]qhedpyikyydt[/url], [link=http://jpvfntnkcajs.com/]jpvfntnkcajs[/link], http://bzedzudfsrzw.com/

# Eaode said on Friday, April 24, 2009 2:17 AM

Can someone repost the source code for this? This seems like an easy way to play audio (and I don't want to just embed WMP <_<) , but the .zip is corrupt or absent.

# Lightygalaxy said on Wednesday, May 20, 2009 7:20 PM

Any One can play aac format file (m4a) using winmm.dll

or I have to use some different Idea

Please Help me !!!

# cheap propecia said on Thursday, May 28, 2009 3:01 PM

It is the coolest site,keep so!

# yuukhtjq said on Monday, June 15, 2009 4:58 PM

Na9miF  <a href="shuhdaejzuqv.com/.../a>, [url=http://bjztayxqfpmq.com/]bjztayxqfpmq[/url], [link=http://mkvswffolrto.com/]mkvswffolrto[/link], http://bcqiiwaccuuv.com/

# Pharme260 said on Wednesday, July 01, 2009 8:26 AM

Very nice site! <a href="oixapey.com/.../1.html">cheap viagra</a>

# Pharmf847 said on Wednesday, July 01, 2009 8:26 AM

Very nice site!  [url=oixapey.com/.../2.html]cheap cialis[/url]

# Pharma445 said on Wednesday, July 01, 2009 8:26 AM

Very nice site! cheap cialis oixapey.com/.../4.html

# Pharmc424 said on Wednesday, July 01, 2009 8:27 AM

Very nice site!

Leave a Comment

(required) 
(required) 
(optional)
(required) 

Enter the numbers above: