Здравствуйте! В сегодняшней статье мы рассмотрим как встроить элемент медиаплеера в Windows Forms, с C#
для воспроизведения видеофайлов.
Шаг 1: Создание нового проекта
Давайте создадим новый проект в Visual Studio с типом WinForms.
- Откройте Visual Studio.
- Создайте новый проект типа «Windows Forms App (.NET Framework)».
Шаг 2: Добавление элемента управления MediaPlayer
-
Перетащите элемент управления WindowsMediaPlayer из панели инструментов на вашу форму.
Если элемент WindowsMediaPlayer не отображается в панели инструментов, вам нужно добавить его вручную. -
Для этого щелкните правой кнопкой мыши на панели инструментов и выберите «Choose Items…».
-
В открывшемся окне найдите WindowsMediaPlayer и добавьте его.
Шаг 3: Настройка формы
Теперь, когда элемент управления WindowsMediaPlayer добавлен на форму, настроим его для воспроизведения видеофайлов.
using System;
using System.Windows.Forms;
using WMPLib; // Пространство имен для Windows Media Player
namespace VideoPlayerApp
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// Установите путь к видеофайлу
string videoPath = @"C:\path\to\your\video.mp4";
axWindowsMediaPlayer1.URL = videoPath;
// Начните воспроизведение
axWindowsMediaPlayer1.Ctlcontrols.play();
}
}
}
Шаг 4: Запуск приложения
Теперь вы можете запустить приложение. При загрузке формы видеофайл начнет воспроизводиться в элементе управления WindowsMediaPlayer
.
Таким образом, мы встроили проcтой видеоплеер в наше окно Windows Forms.
Для тех, кого заинтересовала данная тема рекомендую видеокурс на тему рекомендуем видеокурс Программирование на C# с Нуля до Гуру
-
Создано 23.04.2025 09:09:09
-
Михаил Русаков
Копирование материалов разрешается только с указанием автора (Михаил Русаков) и индексируемой прямой ссылкой на сайт (http://myrusakov.ru)!
Добавляйтесь ко мне в друзья ВКонтакте: http://vk.com/myrusakov.
Если Вы хотите дать оценку мне и моей работе, то напишите её в моей группе: http://vk.com/rusakovmy.
Если Вы не хотите пропустить новые материалы на сайте,
то Вы можете подписаться на обновления: Подписаться на обновления
Если у Вас остались какие-либо вопросы, либо у Вас есть желание высказаться по поводу этой статьи, то Вы можете оставить свой комментарий внизу страницы.
Если Вам понравился сайт, то разместите ссылку на него (у себя на сайте, на форуме, в контакте):
-
Кнопка:
Она выглядит вот так:
-
Текстовая ссылка:
Она выглядит вот так: Как создать свой сайт
- BB-код ссылки для форумов (например, можете поставить её в подписи):
Распознавание голоса и речи на C#
UnmanagedCoder 05.05.2025
Интеграция голосового управления в приложения на C# стала намного доступнее благодаря развитию специализированных библиотек и API. При этом многие разработчики до сих пор считают голосовое управление. . .
Реализация своих итераторов в C++
NullReferenced 05.05.2025
Итераторы в C++ — это абстракция, которая связывает весь экосистему Стандартной Библиотеки Шаблонов (STL) в единое целое, позволяя алгоритмам работать с разнородными структурами данных без знания их. . .
Разработка собственного фреймворка для тестирования в C#
UnmanagedCoder 04.05.2025
C# довольно богат готовыми решениями – NUnit, xUnit, MSTest уже давно стали своеобразными динозаврами индустрии. Однако, как и любой динозавр, они не всегда могут протиснуться в узкие коридоры. . .
Распределенная трассировка в Java с помощью OpenTelemetry
Javaican 04.05.2025
Микросервисная архитектура стала краеугольным камнем современной разработки, но вместе с ней пришла и головная боль, знакомая многим — отслеживание прохождения запросов через лабиринт взаимосвязанных. . .
Шаблоны обнаружения сервисов в Kubernetes
Mr. Docker 04.05.2025
Современные Kubernetes-инфраструктуры сталкиваются с серьёзными вызовами. Развертывание в нескольких регионах и облаках одновременно, необходимость обеспечения низкой задержки для глобально. . .
Создаем SPA на C# и Blazor
stackOverflow 04.05.2025
Мир веб-разработки за последние десять лет претерпел коллосальные изменения. Переход от традиционных многостраничных сайтов к одностраничным приложениям (Single Page Applications, SPA) — это. . .
Реализация шаблонов проектирования GoF на C++
NullReferenced 04.05.2025
«Банда четырёх» (Gang of Four или GoF) — Эрих Гамма, Ричард Хелм, Ральф Джонсон и Джон Влиссидес — в 1994 году сформировали канон шаблонов, который выдержал проверку временем. И хотя C++ претерпел. . .
C# и сети: Сокеты, gRPC и SignalR
UnmanagedCoder 04.05.2025
Сетевые технологии не стоят на месте, а вместе с ними эволюционируют и инструменты разработки. В . NET появилось множество решений — от низкоуровневых сокетов, позволяющих управлять каждым байтом. . .
Создание микросервисов с Domain-Driven Design
ArchitectMsa 04.05.2025
Архитектура микросервисов за последние годы превратилась в мощный архитектурный подход, который позволяет разрабатывать гибкие, масштабируемые и устойчивые системы. А если добавить сюда ещё и. . .
Многопоточность в C++: Современные техники C++26
bytestream 04.05.2025
C++ долго жил по принципу «один поток — одна задача» — как старательный солдатик, выполняющий команды одну за другой. В то время, когда процессоры уже обзавелись несколькими ядрами, этот подход стал. . .
-
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
In this article I will explain with an example, how to use Windows Media Player in Windows Forms (WinForms) Application using C# and VB.Net.
Adding Windows Media Player to Toolbox
Open Visual Studio and Right Click inside the Toolbox and select Add Tab option from the Context Menu.
The Add Tab Button will add a new Tab in the Toolbox and you will need to set a suitable name to it.
Now inside the newly created Tab, you need to Right Click and click Choose Items… from the Context Menu.
Then look for the Windows Media Player within the COM components tab of the Choose Toolbox Items window.
Finally, Click OK and the Windows Media Player control will now be added to the Visual Studio Toolbox.
Video File Location
The Video file is stored inside the disk Folder (Directory).
Form Design
Now drag drop the Windows Media Player to the Form.
Playing Video (MP4) File in Windows Forms using C# and VB.Net
Inside the Form Load event, the path of the video file is set to the media player URL property.
C#
private void Form1_Load(object sender, EventArgs e)
{
axWindowsMediaPlayer1.URL = @»E:\Files\Butterfly.mp4″;
}
VB.Net
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
axWindowsMediaPlayer1.URL = «E:\Files\Butterfly.mp4»
End Sub
Screenshot
Downloads
-
#1
I am trying to add a Media Player (or Windows Media Player) to my C# Form.
I have managed to find it (Windows Media Player) in COM components and added it to my application, but there was a message saying it was not enabled and did not show up in the ToolBox.
I have a feeling this is because I created the project as a Windows Forms App rather than a Windows Form App (.Net Framework).
This was confirmed by creating a new project as a Net Framework one, and the Windows Media Player was in the toolbox.
However, now I run into other problems in that some of the features that worked are not supported in the Net Framework one.
e.g. nullable reference types is not available in C# 7.3, Please use language version 8.0 or greater.
Also, it seems as if the Windows Form App (.Net Framework) is using Net 4.7 whereas the original Windows Forms App is using Net 6.
Sorry this is a bit convoluted, but it is difficult to get simple answers in plain English to explain all this.
I am a bit concerned that if I go to the Windows Form App (.Net Framework) I will be using a legacy system which does not support new language features.
So, basically my question is, do I have to use Windows Form App (.Net Framework) to be able to use Media Player, and if so, how do I create the project with Net 5 or 6 and the language version 8 or 9 maybe?
-
#2
If you target .NET Framework then you don’t «create the project with Net 5 or 6» because they are not .NET Framework. .NET 5 and later are .NET Core. .NET Core 3.1 and .NET Framework 4.8 were being developed concurrently. That was the last version of .NET Framework and the next version of .NET Core was .NET 5. They dropped the «Core» because it was the only game in town so no need to distinguish it and they skipped version 4.x to avoid any further confusion. .NET 5 basically rolled some Framework-specific features into Core so there was really no need for the two any more.
-
#3
If you right-click the Framework project and select Unload Project, you can then edit the project file directly. You can specify the language version yourself there, e.g. here’s one I prepared earlier:
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{86B97037-3A63-4406-89E1-920A1D782172}</ProjectGuid>
<OutputType>Exe</OutputType>
<RootNamespace>Test.Console._481</RootNamespace>
<AssemblyName>Test.Console.481</AssemblyName>
<TargetFrameworkVersion>v4.8.1</TargetFrameworkVersion>
<LangVersion>9</LangVersion>
<FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<Deterministic>true</Deterministic>
<NuGetPackageImportStamp>
</NuGetPackageImportStamp>
</PropertyGroup>
-
#4
If you right-click the Framework project and select Unload Project, you can then edit the project file directly. You can specify the language version yourself there, e.g. here’s one I prepared earlier:
<PropertyGroup> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> <ProjectGuid>{86B97037-3A63-4406-89E1-920A1D782172}</ProjectGuid> <OutputType>Exe</OutputType> <RootNamespace>Test.Console._481</RootNamespace> <AssemblyName>Test.Console.481</AssemblyName> <TargetFrameworkVersion>v4.8.1</TargetFrameworkVersion> <LangVersion>9</LangVersion> <FileAlignment>512</FileAlignment> <AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects> <Deterministic>true</Deterministic> <NuGetPackageImportStamp> </NuGetPackageImportStamp> </PropertyGroup>
Great, thanks. I changed mine to Language Version 9 and the missing features are back.
From what I have read though, I still have to use Net Framework rather then Net 6 because not all Net Framework features (such as Media Player) are available in Net 6.
Also, when creating a new project, there was no option to use Net 6 for c# Desktop applications.
-
#5
In general, the .NET (Core) set of apps were supposed to target apps to run multi-platform: Windows, Mac, Linux. Since there is no Windows Media Player or any other COM-style integration on the latter two, there was no compelling reason to make it available.
Originally, .NET (Core) was not supposed to support WinForms (and WPF support was going to be on for Windows). I think enough companies put pressure on Microsoft to continue to support WinForms, so Microsoft added WinForms in .NET Core 3.x but with the caveat of not a lot of investment was going to go into new feature development for it. So WinForms came in but a lot of the tooling around it didn’t.
-
#6
I am a bit concerned that if I go to the Windows Form App (.Net Framework) I will be using a legacy system which does not support new language features.
The irony of this of course being that you’re concerned about using legacy language that doesn’t allow modern c# features, yet you’re definitely using a legacy media player!
-
#7
The irony of this of course being that you’re concerned about using legacy language that doesn’t allow modern c# features, yet you’re definitely using a legacy media player!
Yes, true. I did notice that Microsoft was suggesting using Media Player instead of Windows Media Player, but I could not find any information as to how to actually do that.
However, that is not a problem now, as I have removed the Windows Media Player from my application and just open up the default Media Player when a video file thumbnail is clicked.
I have now successfully managed to get thumbnails for all image or video files directly from the Thumbnail Cache. The only slight issue is I can’t figure out how to get the Video sprockets on the thumbnail for videos. There is supposed to be an Adornment for this, which Windows Live Photo Gallery clearly uses.
-
#10
What mode are you passing in to the API?
-
#11
What mode are you passing in to the API?
Thanks for the reply. Must admit that my knowledge is not yet that good that I understand the question.
To get the thumbnails, all I do is call shellFile.Thumbnail.LargeBitmap; for the appropriate image.
I see in the link you provided it has the lines :-
[Windows.Foundation.Metadata.Overload("GetThumbnailAsyncOverloadDefaultSizeDefaultOptions")]
[Windows.Foundation.Metadata.RemoteAsync]
public IAsyncOperation<StorageItemThumbnail> GetThumbnailAsync(ThumbnailMode mode);
When I add these to the code, I just get compiler errors. I’m afraid the link is just assuming too much knowledge that I don’t have. It does not explain how you include the items in brackets.
I have noticed this with a lot of Microsoft documentation — its not much use to beginners (even though I have been coding in c# for 15+ years on and off).
I’ll do some more research.
-
#12
What mode are you passing in to the API?
This also only returns the thumbnail, without the adornments. In the Thumbnail Handlers article it said «Adornments are provided by Windows; do not create them yourself», I’m guessing this is something OS/Explorer adds to the views and never to the actual thumbnail.
To test the code create a .Net project (not .Net Framework). I created a Windows Forms .Net 7 project, and in Project Properties the Target OS Version and Supported version must be Windows 10.0.10240.0 or later. Then the Windows.Storage namespace is available:
var file = await StorageFile.GetFileFromPathAsync(filepath);
using var thumb = await file.GetThumbnailAsync(ThumbnailMode.VideosView, 256);
var ext = thumb.ContentType.Split('/')[1];
using var outfile = File.Create("test." + ext);
await thumb.AsStream().CopyToAsync(outfile);
-
#13
This also only returns the thumbnail, without the adornments. In the Thumbnail Handlers article it said «Adornments are provided by Windows; do not create them yourself», I’m guessing this is something OS/Explorer adds to the views and never to the actual thumbnail.
To test the code create a .Net project (not .Net Framework). I created a Windows Forms .Net 7 project, and in Project Properties the Target OS Version and Supported version must be Windows 10.0.10240.0 or later. Then the Windows.Storage namespace is available:
var file = await StorageFile.GetFileFromPathAsync(filepath); using var thumb = await file.GetThumbnailAsync(ThumbnailMode.VideosView, 256); var ext = thumb.ContentType.Split('/')[1]; using var outfile = File.Create("test." + ext); await thumb.AsStream().CopyToAsync(outfile);
Ok, great I’ll give that a try in the next few days. If that works, it look likes I will have to convert my project back to Net 7 if Net Framework does not support this.
Am I right in thinking that Net 7 is the way to go now and Net Framework is a bit obsolete?
-
#14
John, I tried this as you suggested and managed to get it to produce the thumbnail for a .wmv file, but it did not have video sprockets down the side, so maybe as you say it may be something that is added to the views not the thumbnails. So, I’m back to the drawing board for this unless someone knows how Explorer adds the sprockets.
Its not crucial, just a nice to have, so I may abandon this idea.
-
#15
Read on Win32 tutorials on how to put icon overlays. The same concept applies where instead of an icon, you would have bitmap of the sprockets. You just apply the sprockets on the left and right sides of the thumbnail.