Здравствуйте! В этой статье мы рассмотрим, как создать простое приложение для воспроизведения музыки с использованием класса SoundPlayer в C# Windows Forms. SoundPlayer — это часть пространства имен System.Media, которая позволяет воспроизводить звуковые файлы в формате WAV. Хотя SoundPlayer поддерживает только WAV-файлы, это отличный способ начать работу с аудио в .NET.
Шаги для создания музыкального плеера
- Создание нового проекта Windows Forms:
- Откройте Visual Studio.
- Создайте новый проект и выберите «Windows Forms App (.NET Framework)».
-
Назовите проект, например, SimpleMusicPlayer.
-
Добавление элементов управления:
-
Добавьте на форму следующие элементы управления:
- Button для запуска воспроизведения музыки.
- Button для остановки воспроизведения музыки.
- OpenFileDialog для выбора WAV-файла.
-
Использование SoundPlayer для воспроизведения музыки:
- Создайте экземпляр SoundPlayer и используйте его для управления воспроизведением.
Пример кода
using System;
using System.Media;
using System.Windows.Forms;
namespace SimpleMusicPlayer
{
public partial class Form1 : Form
{
private SoundPlayer player;
public Form1()
{
InitializeComponent();
}
private void btnOpenFile_Click(object sender, EventArgs e)
{
using (OpenFileDialog openFileDialog = new OpenFileDialog())
{
openFileDialog.Filter = "WAV Files|*.wav";
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
player = new SoundPlayer(openFileDialog.FileName);
}
}
}
private void btnPlay_Click(object sender, EventArgs e)
{
if (player != null)
{
player.Play();
}
}
private void btnStop_Click(object sender, EventArgs e)
{
if (player != null)
{
player.Stop();
}
}
}
}
Объяснение кода
-
Инициализация SoundPlayer: Экземпляр SoundPlayer создается при выборе файла через
OpenFileDialog
. Это позволяет пользователю выбрать WAV-файл для воспроизведения. -
Воспроизведение музыки: Метод Play класса SoundPlayer используется для воспроизведения звука. Этот метод вызывается при нажатии кнопки «Play».
-
Остановка воспроизведения: Метод Stop используется для остановки воспроизведения. Этот метод вызывается при нажатии кнопки «Stop».
-
OpenFileDialog: Используется для открытия диалогового окна выбора файла, которое позволяет пользователю выбрать WAV-файл для воспроизведения.
Заключение
Этот простой музыкальный плеер демонстрирует базовые возможности класса SoundPlayer
в C#. Хотя SoundPlayer поддерживает только WAV-файлы, он предоставляет удобный способ начать работу с аудио в приложениях на платформе .NET. Вы можете расширить это приложение, добавив управление громкостью, плейлисты или поддержку других аудиоформатов с использованием дополнительных библиотек.
Для большего понимания, рекомендую видеокурс Программирование на C# с Нуля до Гуру, в котором подробнее рассказано об особенностях языка C#
-
Создано 26.03.2025 13:28:57
-
Михаил Русаков
Копирование материалов разрешается только с указанием автора (Михаил Русаков) и индексируемой прямой ссылкой на сайт (http://myrusakov.ru)!
Добавляйтесь ко мне в друзья ВКонтакте: http://vk.com/myrusakov.
Если Вы хотите дать оценку мне и моей работе, то напишите её в моей группе: http://vk.com/rusakovmy.
Если Вы не хотите пропустить новые материалы на сайте,
то Вы можете подписаться на обновления: Подписаться на обновления
Если у Вас остались какие-либо вопросы, либо у Вас есть желание высказаться по поводу этой статьи, то Вы можете оставить свой комментарий внизу страницы.
Если Вам понравился сайт, то разместите ссылку на него (у себя на сайте, на форуме, в контакте):
-
Кнопка:
Она выглядит вот так:
-
Текстовая ссылка:
Она выглядит вот так: Как создать свой сайт
- BB-код ссылки для форумов (например, можете поставить её в подписи):
-
Use
System.Media.SoundPlayer
to Play a Sound inC#
-
Use the
SystemSounds.Play
Method to Play a Sound inC#
-
Embed the Windows Media Player Control in a C# Solution to Play a Sound
-
Add the
Microsoft.VisualBasic
Reference on the C# Project to Play a Sound
This tutorial will teach you how to play audio files or sounds in Windows Forms using C#. You can’t deny sound’s importance in immersing the audience in game development or technical applications.
C# programming offers four primary ways to implement audio files or sounds to your Windows applications, each useful and practical in unique ways. With such a rich platform as .NET
for multiplayer, you can easily create custom sound generators for WAV
or other format files.
Furthermore, it is possible to build a byte-based buffer of the wave files (sound files) directly in memory using C# as the WPF cones with excellent built-in multiplayer (audio) support.
The important thing to understand here is the SoundPlayer
class which plays sound based on WAV
or wave format which makes it not extremely useful instead, the MediaPlayer
and MediaElement
classes allow the playback of MP3 files.
The SoundPlayer
class can help play a sound at a given path at run time as it requires the file path, name, and a reference to the System.Media
namespace.
You can declare a reference to the System.Media
namespace and use SoundPlayer _exp = new SoundPlayer(@"path.wav");
without mentioning the namespace at the object’s declaration.
Afterward, execute it using the Play()
method with something like _exp.Play();
. Most importantly, file operations like playing a sound should be enclosed within appropriate or suitable structured exception handling blocks for increased efficiency and understanding in case something goes wrong; the path name is malformed, read-only sound file path, null
path, and invalid audio file path name can lead to errors and require different exception classes.
using System;
using System.Media; // essential namespace for using `SoundPlayer`
using System.Windows.Forms;
namespace play_sound {
public partial class Form1 : Form {
// Initialize form components
public Form1() {
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e) {}
private void button1_Click(object sender, EventArgs e) {
// object creation and path selection
SoundPlayer player = new SoundPlayer(@"C:\Users\DELL\dark_souls_theme.wav");
// apply the method to play sound
player.Play();
}
}
}
Output:
Use the SystemSounds.Play
Method to Play a Sound in C#
The functionality (SystemSounds
class offers) is one of the simplest ways of implementing sound in your C# applications in addition to its ability to offer different system sounds with a single line of code; SystemSounds.Beep.Play();
.
However, there are some limitations to using the SystemSounds
class as you can only get access to five different system sounds, including; Asterisk
, Beep
, Exclamation
, Hand
, and Question
, and in case, you disable system sound in Windows, this method will not work, and all the sounds will be replaced with silence.
On the other hand, it makes it extremely easy to play sounds the same way your Windows does, and it’s always a good choice that your C# application respects the user’s choice of silence.
Declare a reference to the System.Media
in your C# project or use something like System.Media.SystemSounds.Asterisk.Play();
to play a sound.
using System;
using System.Media; // essential namespace for `SystemSounds`
using System.Windows.Forms;
namespace play_sound {
public partial class Form1 : Form {
// initialize components
public Form1() {
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e) {}
private void button1_Click(object sender, EventArgs e) {
SystemSounds.Asterisk.Play(); // you can use other sounds in the place of `Asterisk`
}
}
}
Output:
The Play()
method plays the sound asynchronously associated with a set of Windows OS sound-event types. You cannot inherit the SystemSounds
class, which provides static methods to access system sounds.
It is a high-level approach that enables C# applications to use different system sounds in typical scenarios that help these applications to seamlessly fit into the Windows environment. It’s possible to customize the sounds in the Sound
control panel so that each user profile can override these sounds.
It is possible to add the Windows Media Player control using Microsoft Visual Studio to play a sound in C#. The Windows Media Player is in the VS Toolbox, and to use its functionality in your C# application, first, add its components to your Windows Form.
Install the latest version of Windows Media Player SDK on your system and access it using your VS toolbox by customizing it from the COM
components to add the Windows Media Player
option. The default name of Windows Media Player in Visual Studio is axWindowsMediaPlayer1
, and you can change it to something more rememberable.
Add the Windows Media Player ActiveX
control to your C# project and implement it in a button-click event. Furthermore, you can choose two modes: an Independent
mode, analogous to the media opened through the Open
method, and a Clock
mode, a media target corresponding timeline and clock entries in the Timing tree, which controls the playback.
using System;
using System.Windows.Media; // essential namespace
using System.Windows.Forms;
namespace play_sound {
public partial class Form1 : Form {
private MediaPlayer audio_player = new MediaPlayer();
public Form1() {
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e) {}
private void button1_Click(object sender, EventArgs e) {
OpenFileDialog dialog_audio = new OpenFileDialog();
dialog_audio.Filter = "MP3 files (*.mp3)|*.mp3|All files (*.*)|*.*";
if (dialog_audio.ShowDialog() == DialogResult.OK) {
audio_player.Open(new Uri(dialog_audio.FileName));
audio_player.Play();
}
}
private void button2_Click(object sender, EventArgs e) {
// to pause audio
audio_player.Pause();
}
private void button3_Click(object sender, EventArgs e) {
// to resume the paused audio
audio_player.Play();
}
}
}
Output:
Most importantly, the MediaPlayer
class inherits Windows Media Player technology to play audio files and system sound in several modern formats. With its help, you can control the playback process of the sound file mentioned in or carried by the MediaPlayer
instance.
Add the Microsoft.VisualBasic
Reference on the C# Project to Play a Sound
The Audio
class is incredibly famous in Visual Basic for playing a sound, and you can benefit from it by using it in C# by including the Visual Basic bindings in your application. However, there is a C#-specific version of the Audio
class called the SoundPlayer
class, but it does not allow easy byte-based buffer building of the wave directly in memory.
Add the Microsoft.VisualBasic
reference to your C# project as an initial step and create an object from the Audio
class like static Audio my_obj = new Audio();
and add the sound file address like my_exp.Play("m:\\path.wav", AudioPlayMode.WaitToComplete);
.
You can customize or set the AudioPlayMode
by yourself, which allows you to customize the playback time of the sound.
using System;
using System.Windows.Forms;
using Microsoft.VisualBasic; // essential namespace
using Microsoft.VisualBasic.Devices; // essential namespace
namespace play_sound {
public partial class Form1 : Form {
static Audio audio_player = new Audio();
public Form1() {
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e) {}
private void button1_Click(object sender, EventArgs e) {
audio_player.Play(@"C:\Users\DELL\dark_souls_theme.wav", AudioPlayMode.WaitToComplete);
}
}
}
Output:
It is a good practice to use the Background
or BackgroundLoop
tool to resume the other tasks while the audio continues to play in the background.
It is optional; however, you can create custom sounds using nothing more than the C# code by learning the uncompressed WAV file and can create the sound directly in your system’s memory.
This tutorial taught you how to effectively play a sound file in C#.
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
-
Subject:
C# Tutorials - Learning Time: 30 minutes
In this tutorial we will demonstrate how to play multiple audio files in Windows Forms with C# programming. Audio is very important to games development, a must have good music and sound effects and they should be blended into the game so the player doesn’t notice them but knows they are there. In the past tutorials we used the Sound Player class to play simple sound effects in games but we haven’t covered a tutorial where you can play the background sound and a sound effect in a game yet. The sound player is very useful but its not practical for games development as the main audio player. For example you cannot play two sound files simultaneously during run time. The sound player class will stop the other sound from playing before loading and playing a new sound file. This is where we can use the Media Player windows form component to ensure have steady music playing in the background and we can mix it up with the sound player class to play any sound effects we want to play in it.
Lesson Objectives –
- Import the media player component to windows forms toolbox
- Use the media player component to Load MP3 files during the run time
- Use sound player and media player together
- Use buttons to control the play and stop functionalities of the media player
- Learn how to repeat sound files or music in the media player with C#
Video
Download the sound files for this project
Full Source Code –
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Media; namespace Play_Mutiple_Sounds_MOO_ICT { public partial class Form1 : Form { SoundPlayer backgroundMusic; SoundPlayer laserSound; bool bgPlaying = false; public Form1() { InitializeComponent(); // set up the media player MXP.URL = @"bg_music_mediaplayer.mp3"; MXP.settings.playCount = 9999; // repeating the music when it ends MXP.Ctlcontrols.stop(); MXP.Visible = false; } private void PlayLaserSound(object sender, EventArgs e) { laserSound = new SoundPlayer(@"laserSound.wav"); laserSound.Play(); } private void PlayBackgroundSoundPlayer(object sender, EventArgs e) { backgroundMusic = new SoundPlayer(@"bg_music.wav"); backgroundMusic.PlayLooping(); MXP.Ctlcontrols.stop(); // stop the media player bgPlaying = true; // set playing to true } private void PlayMediaPlayer(object sender, EventArgs e) { if (bgPlaying == true) { backgroundMusic.Stop(); bgPlaying = false; } MXP.Ctlcontrols.play(); } } }
В этом примере воспроизводится звук по заданному пути во время выполнения.
Пример
Sub PlaySimpleSound()
My.Computer.Audio.Play("c:\Windows\Media\chimes.wav")
End Sub
private void playSimpleSound()
{
SoundPlayer simpleSound = new SoundPlayer(@"c:\Windows\Media\chimes.wav");
simpleSound.Play();
}
Компиляция кода
Для этого примера требуются:
-
замена имени файла
"c:\Windows\Media\chimes.wav"
на допустимое имя файла. -
(C#) Ссылку на System.Media пространства имен.
Отказоустойчивость
Операции с файлами должны быть включены в соответствующие структурированные блоки обработки исключений.
При следующих условиях возможно возникновение исключения:
-
Недопустимое имя пути Например, оно содержит недопустимые символы или состоит из одних пробелов (класс ArgumentException).
-
Путь доступен только для чтения (класс IOException).
-
Имя пути —
null
(класс ArgumentNullException). -
Указано слишком длинное имя пути (класс PathTooLongException).
-
Недопустимый путь (класс DirectoryNotFoundException).
-
Путь содержит только двоеточие, «:» (NotSupportedException класса).
Безопасность платформы .NET Framework
По имени файла не всегда можно с уверенностью судить о его содержимом. Например, файл с именем Form1.vb
может вовсе не быть исходным файлом Visual Basic. Следует проверять все входные данные перед использованием их в приложении.
См. также
- SoundPlayer
- Практическое руководство. Асинхронная загрузка звука в Windows Forms