Play .wav or .mp3 media using c-sharp

- Posted in Coding by
using System;

namespace PlayWav{    

    class Program {                

        static void Main(string[] args)
        {

            Console.Clear();            

            System.Media.SoundPlayer player = new System.Media.SoundPlayer();
            player.SoundLocation = "upbeat.wav";
            player.Play();
            Console.WriteLine("nn Press any key to exit...");
            Console.ReadKey();
        }

    }

}

Now, this is quite handy for small .wav files used as sound effects. But if you're going to play songs, you wanna use .mp3 format. That's not quite as simple. After some research, I found it's not difficult if you use a freely available library called NAudio. Your code must reference this library, whose code is contained in file NAudio.dll. I should note that the following code will suffice equally well whether you wish to play .wav or .mp3 files:

using System;
using NAudio;
using NAudio.Wave;

namespace PlayMp3{   

    class Program {                

        static void Main(string[] args)
        {

            Console.Clear(); 
            Console.WriteLine("n Press a key to play a 7-second segment from 'Somewhere Out There' (a 1986 song)");
            Console.ReadKey();
            using(var audioFile = new AudioFileReader("somewhere.mp3"))
            using(var outputDevice = new WaveOutEvent())
            {
                outputDevice.Init(audioFile);
                outputDevice.Play();
                while (outputDevice.PlaybackState == PlaybackState.Playing)
                {
                    System.Threading.Thread.Sleep(1000);
                }
            }
            Console.WriteLine("nn Press any key to exit...");
            Console.ReadKey();
        }

    }

}

Ensure single instance only using c-sharp

- Posted in Uncategorized by
Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    bool result;
    var mutex = new System.Threading.Mutex(true, "MakeThisAHighlyUniqueString", out result);

if (!result)
{
    MessageBox.Show("Another instance is already running.");
    return;
}           
Application.Run(new MainForm());
GC.KeepAlive(mutex);