WPF C# Tutorial – Playing Audio Files with Sound Player and Media Player in Visual Studio

Full Code –

Here is the full source code of the app. Check against this if you are having problems during the tutorial. Make sure to add the Using System.Media; name space on top of your program as this one is important to use the sound player class in C#. Have fun and stay tuned for more tutorials. Moo Out.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

using System.Media;

namespace play_sound
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        

        public MainWindow()
        {
            InitializeComponent();
        }

        private void playsoundOne(object sender, RoutedEventArgs e)
        {
            // this is the sound player class, we are inseting a new sound file with it from the resources panel
            SoundPlayer playSound = new SoundPlayer(Properties.Resources.cello);
            playSound.Play(); // now it will play the sound file once
            //playSound.PlayLooping(); // This line will keep this file looping take out the comments from the front
        }

        private void playsoundTwo(object sender, RoutedEventArgs e)
        {
            MediaPlayer playMedia = new MediaPlayer(); // making a new instance of the media player
            var uri = new Uri("pack://siteoforigin:,,,/sound/cello.wav"); // browsing to the sound folder and then the WAV file location
            playMedia.Open(uri); // inserting the URI to the media player
            playMedia.Play(); // playing the media file from the media player class

        }
    }
}

 




One response to “WPF C# Tutorial – Playing Audio Files with Sound Player and Media Player in Visual Studio”

  1. Zach Dwyer says:

    Thank you for this! I was trying to use MediaPlayer and it kept failing, but SoundPlayer works great and loaded the file a little quicker I think, too.