Play Wave File (.NET 2.0 Framework)

tayspen 0 Tallied Votes 215 Views Share

Playing a wave file just got a whole lot easier.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Media;//Make sure you have this.

namespace WindowsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            SoundPlayer player = new SoundPlayer();
            string path = "C:\\windows\\media\\ding.wav"; 
            player.SoundLocation = path; //Set the path
            player.Play(); //play it
        }
    }
}

Dani AI

Generated

is right — playing a WAV in .NET 2.0 is simple, but a few practical tips make it robust and easier to ship. SoundPlayer (the class used in the C# sample) is intended for .wav files only and is very lightweight: it can play asynchronously, synchronously or loop, but it does not support MP3 or provide volume/position controls.

For VB.NET the shortest, idiomatic option is the My API. Example (background play, non-blocking):

Try
    My.Computer.Audio.Play("yourSound.wav", AudioPlayMode.Background)
Catch ex As Exception
    ' handle missing file or unsupported format
End Try

If you embed sounds in project resources you can pass the resource stream/object instead of a disk file (use My.Resources.YourSound with AudioPlayMode.Background or WaitToComplete).

Troubleshooting & deployment notes you won't find in the single example above:

  • Play() is asynchronous; PlaySync() blocks the calling thread. Use Background/WaitToComplete accordingly to avoid freezing the UI.
  • If you use SoundPlayer with a Stream keep that stream open until playback finishes — SoundPlayer reads from it while playing.
  • Confirm the file exists and is a valid WAV; compressed WAVs may require codecs. MP3s won't play with SoundPlayer.
  • For relative paths prefer Application.StartupPath or put the WAV in resources so the path is not machine-dependent.
  • SoundPlayer/My.Computer.Audio do not provide volume or advanced controls; for volume/position/format conversions use a multimedia library such as NAudio or host the Windows Media Player control.

These pointers let the simple example scale to real apps: pre-load when appropriate, catch file/format errors, and pick a richer API when you need more than a basic beep.

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.