Hello dears.
I need to play a music in my projects background.
I did such below but it does not work.
what is problem please?

class PlayMusic
{
    private string cmd;
    private bool isOpen;
    [DllImport("winmm.dll")]
    private static extern long mciSendString(string strCommand,StringBuilder strReturn,int iReturnLength, IntPtr hwndCallback);

    public void Close()
        {
            cmd = "close MediaFile";
            mciSendString(cmd, null, 0, IntPtr.Zero);
            isOpen = false;
        }

    public void Open(string sFileName)
        {
            cmd = "open "+ sFileName +" type mpegvideo alias MediaFile";
            mciSendString(cmd, null, 0, IntPtr.Zero);
            isOpen = true;
        }

    public void Play(bool loop)
        {
            if (isOpen)
            {
                cmd = "play MediaFile";
                mciSendString(cmd, null, 0, IntPtr.Zero);

                if (loop)
                    cmd = " REPEAT";
                mciSendString(cmd, null, 0, IntPtr.Zero);
            }
        }
    }

my headers are :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;

and my playing action is:

PlayMusic pm = new PlayMusic();
pm.Open("c:\test.mp3");
pm.Play(true);

when I do it it do nothing.I dont know what is the probleme.
Thanks if help me dears.

Why do you have to go through the whole interop thing when you can use .NET build-in features to play back audio files? you can use the windows media player object available to you for free, use the DirectX audio or even use the vlc one (although its not easy to get it working) but those are the best ones you'd wanna invest you time on instead of working with legacy code written in C from the WIN API

That soundplayer class in the system.media namespace is basically an interlop class that calls this very api. There's nothing wrong with using it. The reason it doesn't work appears to be the command strings. But the link ange1ofD4rkness posted is a great code snippet and if you search the DaniWeb C# code snippet library there are at least 3 code snippets for playing sounds there.

Good luck.

Change the open command to by removing the type and this works for me.

cmd = "open "+ sFileName +" alias MediaFile";
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.