C#
.NET
sound playback
programming
audio handling

How to play a sound in C, .NET

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

C# and .NET provide several ways to play audio, from the simple System.Media.SoundPlayer (WAV only, Windows) to the cross-platform NAudio library (WAV, MP3, and more) and the modern Windows.Media.Playback API for UWP/WinUI apps. The right choice depends on the audio format, platform, and complexity — SoundPlayer for simple WAV alerts, NAudio for full audio control, and MediaPlayer for modern Windows apps.

System.Media.SoundPlayer (Simplest — WAV Only)

csharp
1using System.Media;
2
3// Play a WAV file
4SoundPlayer player = new SoundPlayer(@"C:\sounds\alert.wav");
5
6// Synchronous — blocks until playback completes
7player.PlaySync();
8
9// Asynchronous — returns immediately
10player.Play();
11
12// Loop continuously
13player.PlayLooping();
14
15// Stop playback
16player.Stop();

Play from an embedded resource:

csharp
// Sound file added as embedded resource in project
SoundPlayer player = new SoundPlayer(Properties.Resources.alert);
player.Play();

Play system sounds:

csharp
1SystemSounds.Beep.Play();
2SystemSounds.Asterisk.Play();
3SystemSounds.Exclamation.Play();
4SystemSounds.Hand.Play();
5SystemSounds.Question.Play();

SoundPlayer only supports WAV format. It is Windows-only and not available in .NET MAUI or cross-platform projects.

Console.Beep (Simplest Possible)

csharp
1// Simple beep at default frequency
2Console.Beep();
3
4// Custom frequency (Hz) and duration (ms)
5Console.Beep(440, 500);   // A4 note for 500ms
6Console.Beep(523, 500);   // C5 note for 500ms
7Console.Beep(659, 500);   // E5 note for 500ms

Console.Beep(frequency, duration) is Windows-only and blocks the thread for the specified duration.

NAudio supports WAV, MP3, AIFF, WMA, and more:

bash
dotnet add package NAudio
csharp
1using NAudio.Wave;
2
3// Play a WAV file
4using var audioFile = new AudioFileReader(@"C:\music\song.wav");
5using var outputDevice = new WaveOutEvent();
6outputDevice.Init(audioFile);
7outputDevice.Play();
8
9// Wait for playback to complete
10while (outputDevice.PlaybackState == PlaybackState.Playing)
11{
12    Thread.Sleep(100);
13}

Play MP3:

csharp
1using var audioFile = new AudioFileReader(@"C:\music\song.mp3");
2using var outputDevice = new WaveOutEvent();
3outputDevice.Init(audioFile);
4outputDevice.Play();
5
6// Event-based completion
7outputDevice.PlaybackStopped += (sender, args) =>
8{
9    Console.WriteLine("Playback finished");
10};

NAudio with Volume and Position Control

csharp
1using NAudio.Wave;
2
3var audioFile = new AudioFileReader(@"C:\music\song.mp3");
4var outputDevice = new WaveOutEvent();
5
6// Set volume (0.0 to 1.0)
7outputDevice.Volume = 0.5f;
8
9outputDevice.Init(audioFile);
10outputDevice.Play();
11
12// Seek to a position
13audioFile.CurrentTime = TimeSpan.FromSeconds(30);
14
15// Get duration
16Console.WriteLine($"Duration: {audioFile.TotalTime}");
17Console.WriteLine($"Position: {audioFile.CurrentTime}");
18
19// Pause and resume
20outputDevice.Pause();
21outputDevice.Play();
22
23// Stop and cleanup
24outputDevice.Stop();
25outputDevice.Dispose();
26audioFile.Dispose();

Windows.Media.Playback (UWP / WinUI)

For modern Windows apps:

csharp
1using Windows.Media.Playback;
2using Windows.Media.Core;
3
4var player = new MediaPlayer();
5player.Source = MediaSource.CreateFromUri(new Uri("ms-appx:///Assets/sound.mp3"));
6player.Play();
7
8// With volume
9player.Volume = 0.7;
10
11// Event handling
12player.MediaEnded += (sender, args) =>
13{
14    Console.WriteLine("Playback complete");
15};

Cross-Platform with .NET MAUI

csharp
1// .NET MAUI Community Toolkit provides audio support
2// Install: dotnet add package CommunityToolkit.Maui
3
4using CommunityToolkit.Maui.Alerts;
5
6// Simple audio
7var audioPlayer = AudioManager.Current.CreatePlayer(
8    await FileSystem.OpenAppPackageFileAsync("sound.mp3"));
9audioPlayer.Play();
10
11// With duration tracking
12audioPlayer.PlaybackEnded += (s, e) => Console.WriteLine("Done");

Playing Audio from a Stream

csharp
1using NAudio.Wave;
2
3// From a byte array
4byte[] audioData = File.ReadAllBytes("sound.wav");
5using var ms = new MemoryStream(audioData);
6using var reader = new WaveFileReader(ms);
7using var output = new WaveOutEvent();
8output.Init(reader);
9output.Play();
10
11// From an HTTP stream
12using var httpClient = new HttpClient();
13using var stream = await httpClient.GetStreamAsync("https://example.com/sound.mp3");
14using var reader2 = new Mp3FileReader(stream);
15using var output2 = new WaveOutEvent();
16output2.Init(reader2);
17output2.Play();

Comparison

MethodFormatsPlatformAsyncComplexity
SoundPlayerWAV onlyWindowsYes (Play)Minimal
Console.BeepTone onlyWindowsNo (blocking)Trivial
NAudioWAV, MP3, AIFF, WMAWindowsYesMedium
MediaPlayer (WinUI)MP3, WAV, AAC, etc.Windows 10+YesMedium
MAUI AudioManagerPlatform-dependentCross-platformYesMedium

Common Pitfalls

  • Using SoundPlayer for MP3 files: SoundPlayer only supports uncompressed WAV. Attempting to play an MP3 produces silence or an exception. Use NAudio or MediaPlayer for MP3 playback.
  • Not disposing audio resources: WaveOutEvent, AudioFileReader, and SoundPlayer hold unmanaged audio device handles. Failing to dispose them causes resource leaks and may block other audio playback. Always use using statements.
  • Blocking the UI thread with PlaySync(): SoundPlayer.PlaySync() blocks the calling thread until the sound finishes. In a GUI app, this freezes the UI. Use Play() (async) or run playback on a background thread.
  • NAudio not available on Linux/macOS: NAudio uses Windows audio APIs (WaveOut, WASAPI, DirectSound). For cross-platform audio, use libraries like OpenAL bindings, SDL2, or the MAUI Community Toolkit.
  • Volume set to zero by default: Some audio APIs default to zero volume or muted state. Always set outputDevice.Volume or check system mixer settings if you hear no sound.

Summary

  • Use SoundPlayer for simple WAV alerts on Windows — minimal code, no external packages
  • Use Console.Beep() for basic tone generation — no files needed
  • Use NAudio for MP3 playback, volume control, seeking, and advanced audio features on Windows
  • Use Windows.Media.Playback.MediaPlayer for UWP and WinUI applications
  • Use the MAUI Community Toolkit for cross-platform audio in .NET MAUI apps
  • Always dispose audio objects with using to prevent resource leaks

Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.