21 Haz

Play Mp3 And Wav Files As Synchronous And Asynchronous In C#

Play A Wav File
SoundPlayer class in System.Media namespace controls playback of a sound from a .wav file. To play the Wav file, you should create a new SoundPlayer object. Then you should set the SoundLocation property to the location of your WAV file, and then use the Play method to play it.

Sample Usage:

            
            System.Media.SoundPlayer player = new System.Media.SoundPlayer();
            player.SoundLocation = @"C:\Test\CSharpExamplesSound.wav";
            player.Play(); //in another thread
            player.PlaySync(); //in same thread

“Play” method in SoundPlayer class plays the .wav file using a new thread. But “PlaySync” method in SoundPlayer plays thw .wav file in same thread.

Play a MP3 File
Above example only plays the .wav files. If you want to play “.mp3” or any other files are supported by windows media player, you can use MediaPlayer class. To use this class, you must add a reference to MedialPlayer.

Add Windows Media Player Reference

Sample Usage:

            
            var mediaPlayer = new MediaPlayer.MediaPlayer();
            mediaPlayer.FileName = @"C:\Test\CSharpExamplesSound.mp3";
            mediaPlayer.Play();

16 Haz

Download Files Synchronous And Asynchronous From A URL in C#

This page tells how to download files from any url to local disk. To download the files, We use WebClient class in System.Net namespace. This class supports to the synchronous and asynchronous downloads. Following examples show how to download files as synchronous and asynchronous.

This example downloads the resource with the specified URI to a local file.

            using (WebClient webClient = new WebClient())
            {
                webClient.DownloadFile("http://www.example.com/file/test.jpg", "test.jpg");
            }

This example downloads to a local file, the resource with the specified URI. Also this method does not block the calling thread.

            using (WebClient webClient = new WebClient())
            {
                webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(delegate(object sender, DownloadProgressChangedEventArgs e)
                    {
                        Console.WriteLine("Downloaded:" + e.ProgressPercentage.ToString());
                    });

                webClient.DownloadFileCompleted += new System.ComponentModel.AsyncCompletedEventHandler
                    (delegate(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
                    {
                        if(e.Error == null && !e.Cancelled)
                        {
                            Console.WriteLine("Download completed!");
                        }
                    });
                webClient.DownloadFileAsync(new Uri("http://www.example.com/file/test.jpg"), "test.jpg");
            }