Play MP3 Files Using C#

Play MP3 Files Using C#
This code uses the Windows Multimedia API winmm.dll library to play MP3 files. Put it into a class and call the Open() method with a parameter specifying the MP3 file that you wish to play.
1. private string _command;
2. private bool isOpen;
3. [DllImport("winmm.dll")]
4. 
5. private static extern long mciSendString(string strCommand,StringBuilder strReturn,int iReturnLength, IntPtr hwndCallback);
6. 
7. public void Close()
8. {
9.     _command = "close MediaFile";
10.    mciSendString(_command, null, 0, IntPtr.Zero);
11.    isOpen = false;
12. }
13. 
14. public void Open(string sFileName)
15. {
16.    _command = "open \"" + sFileName + "\" type mpegvideo alias MediaFile";
17.    mciSendString(_command, null, 0, IntPtr.Zero);
18.    isOpen = true;
19. }
20. 
21. public void Play(bool loop)
22. {
23.    if(isOpen)
24.    {
25.       _command = "play MediaFile";
26.       if (loop)
27.        _command += " REPEAT";
28.       mciSendString(_command, null, 0, IntPtr.Zero);
29.    }
30. }
Nathan Pakovskie is an esteemed senior developer and educator in the tech community, best known for his contributions to Geekpedia.com. With a passion for coding and a knack for simplifying complex tech concepts, Nathan has authored several popular tutorials on C# programming, ranging from basic operations to advanced coding techniques. His articles, often characterized by clarity and precision, serve as invaluable resources for both novice and experienced programmers. Beyond his technical expertise, Nathan is an advocate for continuous learning and enjoys exploring emerging technologies in AI and software development. When he’s not coding or writing, Nathan engages in mentoring upcoming developers, emphasizing the importance of both technical skills and creative problem-solving in the ever-evolving world of technology. Specialties: C# Programming, Technical Writing, Software Development, AI Technologies, Educational Outreach

Leave a Reply

Your email address will not be published. Required fields are marked *

Back To Top