音乐播放器-C#实现
目录
一、 代码介绍
二、 音乐播放器-C#实现
三、 音乐播放器-C#实现
四、 音乐播放器-C#实现
五、 音乐播放器-C#实现
代码中使用了.NET框架中的`System.Media`命名空间来处理音频文件的播放和控制。这段代码创建了一个简单的音乐播放器界面,包括打开文件、播放、暂停、恢复和停止按钮。通过使用`SoundPlayer`类,可以加载并播放音频文件。用户可以通过点击相应的按钮来控制音乐的播放状态
using System;
using System.IO;
using System.Windows.Forms;
using System.Media;
namespace MusicPlayer
{
public partial class MainForm : Form
{
private SoundPlayer player;
private string currentFilePath;
public MainForm()
{
InitializeComponent();
}
private void btnOpen_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "音频文件|*.wav;*.mp3";
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
currentFilePath = openFileDialog.FileName;
lblFileName.Text = Path.GetFileName(currentFilePath);
PlayMusic();
}
}
private void PlayMusic()
{
if (player != null)
{
player.Stop();
player.Dispose();
}
player = new SoundPlayer(currentFilePath);
player.Play();
}
private void btnPause_Click(object sender, EventArgs e)
{
if (player != null && player.PlaybackState == PlaybackState.Playing)
{
player.Pause();
}
}
private void btnResume_Click(object sender, EventArgs e)
{
if (player != null && player.PlaybackState == PlaybackState.Paused)
{
player.Resume();
}
}
private void btnStop_Click(object sender, EventArgs e)
{
if (player != null)
{
player.Stop();
}
}
}
}