Плеер на си шарп

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Music player that plays mp3 and wav files. Created using Window Forms with C#.NET.

plautz/winforms-music-player

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Читайте также:  List item class css

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

Windows Forms Music Player (C#.NET 4.5.2)

Created for a C# course at Ohio State. This program is a simple music player that plays mp3 and wav music files. The application perserves data state by reading/writing .audio files. A file can have any amount of artists and each artist can have any amount of songs. Each song has a title, artist, and music file. Additionally, an album artwork image can be attached to each song.

Audio is played using the NAudio .NET library.

Welcome screen (some text is old)

Adding a new song

While a song is playing

About

Music player that plays mp3 and wav files. Created using Window Forms with C#.NET.

Источник

Воспроизведение mp3 на C#: пример и плеер

Для большинства проектов, которые я делаю, уже есть готовые решения в сети. Точнее, не совсем готовые, а как бы кубиками, пазлами, частями конструктора – мне надо просто их собрать все вместе. Это, например, относится и к проекту по созданию встроенного в программу на C# mp3 плеера – все элементы готовы, надо только грамотно скомпоновать и запустить.

Итак, для одного проекта потребовалось воспроизведение аудиозаписей. Ну что ж, так как никаких дополнительных требований заказчик не выдвигал, то идем по самому простому пути: подключаем Interop.WMPLib (wmp.dll) – стандартный плеер, который есть в любой версии Windows. Работать с ним до смешного просто. Инициализируем:

static int PlayPause = 0; WMPLib.WindowsMediaPlayer pl = new WMPLib.WindowsMediaPlayer();

Далее, в кнопки обработчика вставляем что-то типа этого:

if (PlayPause == 0) < PlayPause = 1; timer1.Start(); >else if (PlayPause == 1) < pl.controls.pause(); PlayPause = 2; timer1.Stop(); >else if (PlayPause == 2)

Здесь переменная PlayPause хранит состояние проигрывателя. 0 – стоп, 1 – играет, 2 – пауза. Теперь код таймера:

private void timer1_Tick(object sender, EventArgs e)

Не забывает также при загрузке формы установить интервал для таймера:

private void Form1_Load(object sender, EventArgs e) < timer1.Interval = 1000; //Таймер для плеера >

Что мы сделали? Теперь, по нажатию кнопок у нас будет запускаться/останавливаться музыка, а также на ползунке изменяться положение. Но что если нам самим захочется управлять позицией проигрывания? Это просто:

private void trackBar1_Scroll(object sender, EventArgs e)

Теперь у нас имеется практически полноценный аудиоплеер в разрабатываемой программе:

Если вам требуется создать программу на заказ, то вы можете обратиться ко мне. Я пишу на C#, C++, Java. Занимаюсь как учебными программами, так и разрабатываю полноценные приложения, которые используются в реальной работе. Пишите на почту up777up@yandex.ru или сразу в скайп up777up2, вконтакте. Я с удовольствием вам помогу за разумные деньги – мои расценки выгодно отличаются от других программистов, а опыта и различных наработок немало.

Автор этого материала — я — Пахолков Юрий. Я оказываю услуги по написанию программ на языках Java, C++, C# (а также консультирую по ним) и созданию сайтов. Работаю с сайтами на CMS OpenCart, WordPress, ModX и самописными. Кроме этого, работаю напрямую с JavaScript, PHP, CSS, HTML — то есть могу доработать ваш сайт или помочь с веб-программированием. Пишите сюда.

заметки, си шарп, mp3, visual studio

Бесплатный https и
домен RU в подарок

Источник

Mp3 Player in C#

mp3 player

Mp3 Player in C# can be created without using a media control. In most of tutorials you’ve learned designing Mp3 player in C# using Windows Media Player control. But in this tutorial we are not going to use that approach.

Tools Required:

  1. Visual Studio 2010 or Later version.
  2. Pichon desktop app (Optional) for icons. Download it from Here

Steps to Follow:

  1. After creating a new project in Windows Forms App in Visual Studio right click on project file and Add a new class file.
  2. Name that class as Mp3Player.cs and add the following code.
[DllImport("winmm.dll")] private static extern long mciSendString(string lpstrCommand, StringBuilder lpstrReturnString,int uReturnLength,int hwdCallBack); public void open(string File) < string Format = @"open """" type MPEGVideo alias MediaFile"; string command = string.Format(Format,File); mciSendString(command, null, 0, 0); > public void play() < string command = "play MediaFile"; mciSendString(command, null, 0, 0); >public void stop()

In the above code, mciSendString will handle our commands to Load, Play or Stop our audio file.

Open method will load and prepare the audio file. The play and stop method can be used to play or stop the audio file respectively.

Open the design view of your form and add three buttons to open, play and stop the audio file.

Double click on Open button to create OnClick Event. But before adding the code inside this event, First of all create an instance of Mp3Player class on the top of Form1.cs class like,

private Mp3Player mp3Player = new Mp3Player();

and add the follwing code inside the onClick event of Open button:

using (OpenFileDialog ofd = new OpenFileDialog())
ofd.Filter = “Mp3 Files|*.mp3”;
if (ofd.ShowDialog() == DialogResult.OK)
mp3Player.open(ofd.FileName);
>
>

This will open a file dialog box to select your mp3 file.

Now go to the On Click event of Play Button and call the play method of Mp3Player class.

Now go to the click event of stop button and call the stop method of Mp3Player class.

Video Tutorial:

C# - Designing an Mp3 Player in Winform App

Source Code:

I hope you enjoyed this tutorial. Thanks for visiting us.

Please don’t forget to subscribe our official YouTube Channel C# Ui Academy

11 Replies to “Mp3 Player in C#”

It’s hard to find knowledgeable people on this topic, but you sound like you know what you’re talking about! Thanks

maknyus, postingan ini sangat mudah dimengerti. saya jadi mengetahui banyak hal dari artikel ini. cool.

Pretty amazing post. I stumbled upon your blog and wished to say that I’ve really enjoyed reading your blog post. After all I’ll be subscribing to your rss feed and I hope you write again soon!

Pretty nice post. I stumbled upon your post and wished to say that I’ve really enjoyed reading your blog post. After all I’ll be subscribing to your rss feed and I hope you write again soon!

Magnificent items from you, man. I have consider your stuff previous to and you are simply too great. I actually like what you have got here, really like what you are stating and the way in which during which you say it. You’re making it entertaining and you still take care of to stay it smart. I can’t wait to read much more from you. This is really a great site.

cool post. I just stumbled upon your post and wished to say that I’ve really enjoyed reading your blog post. After all I’ll be subscribing to your rss feed and I hope you write again soon!

Источник

Lesson 18 — Audio/Video Player in C# and WPF — Basis

In the previous lesson, Resources in C# .NET WPF, we took a look at resources. One of the interesting WPF controls is , which is used to play audio and video files. In today’s C# .NET WPF, we’re going to describe how to create a simple player.

Features

First of all, we should be clear about what functionality we want for the player. And so that we don’t get overwhelmed, we’ll start from simple ones and move to the more complex ones later. The final project will be a fully featured video and music player, on which we’ll practice, among other things, control styling:

Video player in C# .NET WPF

The application will also support playlists and other features:

Working with music playlists in C# .NET WPF

Let’s say we want the following functionalities for the start:

That might be enough to get started. Later, we can add more, such as volume control, skipping forward and backward, etc. Let’s stop talking and start doing! We’ll create a new WPF project in Visual Studio named AVPlayer .

Layout

MainWindow.xaml with the form design will be displayed. We’ll put a in it and specify the window size:

 x:Class="AVPlayer.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:AVPrehravac" mc:Ignorable="d" Title="MainWindow" Height="450" Width="800">   

:)

And we’re basically done But when we run the application, we can see that we don’t see anything. That’s because we forgot to tell the what we want to play. This is done using the Source property, in which we specify the file path.

At this moment, the file would play, but we’d soon find out that the player plays the same thing over and over again like a broken record. So we’ll add a button to choose the file to the form, and a button to close the application. We’ll use a container to keep things nice and neat:

 x:Name="wdwPlayer" x:Class="AVPlayer.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:AVPrehravac" mc:Ignorable="d" Title="MainWindow" Height="470" Width="700">  Margin="0,20,0,0">  Height="*"/>  Height="10"/>  Height="30"/>  Height="10"/>   x:Name="avPlayer"/>  Grid.Row="2" Margin="20,0">  Width="50"/>  Width="*"/>  Width="80"/>   Grid.Column="0" Content="Open file" Click="BtnOpen" ToolTip="Select a video file"/>  Grid.Column="5" Content="Close" Click="CloseWindow" ToolTip="Close application"/>   

In addition to these two buttons, we also specified the window name, so we can now close it with the button. We also named the , so we can play a specified file in it. Notice that the buttons already have the handler methods set, so let’s add them.

Code Behind

We’ll go to MainWindow.xaml.cs and add the handler method for the button that opens the media file:

private void BtnOpen(object sender, RoutedEventArgs e) < OpenFileDialog openFileDialog = new OpenFileDialog(); openFileDialog.Filter = "Video files (*.mpg;*.mpeg;*.avi;*.mp4)|*.mpg;*.mpeg;*.avi;*.mp4"; if (openFileDialog.ShowDialog() == true) < avPlayer.Source = new Uri(openFileDialog.FileName); > >

Be sure to add the appropriate using for the dialog:

The method opens a file selection dialog and assigns the selected file to the using its Source property. Here, we’ve limited the selection to video files only, using the filter. After the file is assigned, the starts playing the file.

The second method will handle the close button:

private void CloseWindow(object sender, RoutedEventArgs e)

We terminate the application by telling it to close the main window (see the window name wdwPlayer ).

Control Buttons

But at the beginning, we decided that we’d like to be able to pause the video and resume it at any time. So we’ll add more buttons to the app to start the playback, pause it, and stop it.

XAML

We’ll put the buttons into our Grid :

 Grid.Row="2" Margin="20,0">  Width="50"/>  Width="50"/>  Width="50"/>  Width="50"/>  Width="*"/>  Width="80"/>   x:Name="btnOpen" Grid.Column="0" Content="Open" Click="BtnOpen" ToolTip="Select a video file"/>  x:Name="btnPlay" Grid.Column="1" Content="Play" Click="BtnPlay" ToolTip="Plays the video"/>  x:Name="btnPause" Grid.Column="2" Content="Pause" Click="BtnPause" ToolTip="Pauses the video playing"/>  x:Name="btnClose" Grid.Column="3" Content="Close" Click="BtnClose" ToolTip="Closes the video"/>  Grid.Column="5" Content="Close" Click="CloseWindow" ToolTip="Close aplication"/> 

We added three more columns to the container and placed the buttons in them. We’ll modify the as well:

 x:Name="avPlayer" LoadedBehavior="Manual"/>

We changed the predefined LoadedBehavior property from Play to Manual . This allows us to control the player manually.

Code Behind

We’ll extend the file with handler methods with the new methods:

private void BtnPlay(object sender, RoutedEventArgs e) < avPlayer.Play(); >private void BtnPause(object sender, RoutedEventArgs e) < avPlayer.Pause(); >private void BtnClose(object sender, RoutedEventArgs e)

:)

Basically, we’re finished. Next time, in the lesson Audio/Video Player in C# and WPF — Code Improvements, we’ll improve the player code and we’ll work on its appearance

Download

Downloaded 1200x (568.23 kB)

Источник

Оцените статью