2
votes

I know there are a dozen questions like this and I looked at the more popular ones, but I have had no luck in figuring out anything.

I want to make a C# *.exe that would play a sound when opened, I decided it would be OK to start with a Console Application project, but I have no idea if that is the best choice.

I have added the "file.mp3" file to the resource designer under "Other" files and set its build action to "Embedded Resource".

From there I saw the suggestion about WMPLib, which I cannot access in my project - it is not present neither in my Reference Manager, neither does "using WMPLib;" work (it raises a "could not be found" error) or the one about the "System.Media.SoundPlayer.Play();" method but I am having trouble implementing it, because my complier either says an object reference is required for it or it has no overload, because it only takes 1 arguments if I make it like "System.Media.SoundPlayer.Play("file.mp3");"

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Program p = new Program();
            p.Mum();
        }
        void Mum()
        {
            System.Media.SoundPlayer.Play();
        }
    }
}
1
You need to actually create a SoundPlayer... Play() isn't a static method... Look at the MDSN docsBroots Waymb
I take it you have added the reference to that library in your project?user4843530
Furthermore your ressource should be passed in SoundPlayer constructor or by calling the Load(); method. You cant pass it to Play();Bgl86
Also, from that link I posted, SoundPlayer is not able to play mp3's. "The SoundPlayer class cannot play other file types, such as .wma or .mp3. If you want to play other file types, you can use the Windows Media Player control."Broots Waymb

1 Answers

2
votes

To play an mp3 file, You will need to add the windows media player Library. 1. Add a reference to the WMP library - in your solution explorer, under your project, go to References, right click and add a reference to WMP. It will be under the COM libraries, I think. 2. Add "using WMPLib;" to your code at the top, 3. Add this code to play the file:

        WindowsMediaPlayer myplayer = new WindowsMediaPlayer();
        myplayer.URL = "mysound.mp3";
        myplayer.controls.play();

mind you the URL is the path to the file you want to play. If it has backslashes in it, you will have to "escape" them. Like this

 myplayer.URL = "C:\\Users\\Public\\Music\\Sample Music\\Kalimba.mp3";