XAML页面
<Window x:Class="音乐播放界面.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:音乐播放界面"
mc:Ignorable="d"
Title="音乐播放器" Height="800" Width="1200" ResizeMode="NoResize" WindowStartupLocation="CenterScreen" Loaded="Window_Loaded" Icon="img/yin.ico">
<Grid x:Name="bj">
<Grid.Background>
<ImageBrush ImageSource="img/1.jpg"></ImageBrush>
</Grid.Background>
<Grid.RowDefinitions>
<RowDefinition Height="27"></RowDefinition>
<RowDefinition Height="600"></RowDefinition>
<RowDefinition></RowDefinition>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="300"></ColumnDefinition>
<ColumnDefinition></ColumnDefinition>
</Grid.ColumnDefinitions>
<Menu Grid.Row="0" Grid.Column="0" Background="Transparent">
<MenuItem>
<MenuItem.Header>
<Label>文件</Label>
</MenuItem.Header>
<MenuItem.Icon>
<Image Source="img/Query.ico"></Image>
</MenuItem.Icon>
<MenuItem x:Name="DR" Click="DR_Click">
<MenuItem.Header>
<Label>导入音乐</Label>
</MenuItem.Header>
<MenuItem.Icon>
<Image Source="img/open.ico"></Image>
</MenuItem.Icon>
</MenuItem>
<MenuItem Click="MenuItem_Click_11">
<MenuItem.Header>
<Label>清空播放列表</Label>
</MenuItem.Header>
<MenuItem.Icon>
<Image Source="img/sc.png"></Image>
</MenuItem.Icon>
</MenuItem>
<MenuItem Click="MenuItem_Click_4" >
<MenuItem.Header>
<Label>退出</Label>
</MenuItem.Header>
<MenuItem.Icon>
<Image Source="img/Close.png"></Image>
</MenuItem.Icon>
</MenuItem>
</MenuItem>
<MenuItem>
<MenuItem.Header>
<Label>系统设置</Label>
</MenuItem.Header>
<MenuItem.Icon>
<Image Source="img/Update.png"></Image>
</MenuItem.Icon>
<MenuItem>
<MenuItem.Header>
<Label>设置背景</Label>
</MenuItem.Header>
<MenuItem.Icon>
<Image Source="img/v.png"></Image>
</MenuItem.Icon>
<MenuItem Click="MenuItem_Click" Tag="春">
<MenuItem.Header>
<Label>春</Label>
</MenuItem.Header>
</MenuItem>
<MenuItem Click="MenuItem_Click_1" Tag="夏">
<MenuItem.Header>
<Label>夏</Label>
</MenuItem.Header>
</MenuItem>
<MenuItem Click="MenuItem_Click_2" Tag="秋">
<MenuItem.Header>
<Label>秋</Label>
</MenuItem.Header>
</MenuItem>
<MenuItem Click="MenuItem_Click_3" Tag="冬">
<MenuItem.Header>
<Label>冬</Label>
</MenuItem.Header>
</MenuItem>
<Separator></Separator>
<MenuItem Click="MenuItem_Click_10" Tag="自定义">
<MenuItem.Header>
<Label>自定义背景</Label>
</MenuItem.Header>
</MenuItem>
</MenuItem>
<MenuItem>
<MenuItem.Header>
<Label>设置字体</Label>
</MenuItem.Header>
<MenuItem.Icon>
<Image Source="img/bb.png"></Image>
</MenuItem.Icon>
<MenuItem Click="MenuItem_Click_8">
<MenuItem.Header>
<Label>字体放大</Label>
</MenuItem.Header>
</MenuItem>
<MenuItem Click="MenuItem_Click_9">
<MenuItem.Header>
<Label>字体放小</Label>
</MenuItem.Header>
</MenuItem>
</MenuItem>
</MenuItem>
</Menu>
<TreeView Grid.Column="0" Background="Transparent" x:Name="tre" Margin="0,27,0,0.4" Grid.RowSpan="2">
<TreeViewItem x:Name="MusicList">
<TreeViewItem.Header>
<Label>音乐库</Label>
</TreeViewItem.Header>
<TreeViewItem.ContextMenu>
<ContextMenu>
<MenuItem Header="添加到我喜欢" Click="MenuItem_Click_5"></MenuItem>
<MenuItem Header="删除" Click="MenuItem_Click_6"></MenuItem>
</ContextMenu>
</TreeViewItem.ContextMenu>
</TreeViewItem>
<TreeViewItem Name="love">
<TreeViewItem.Header>
<Label>我喜欢</Label>
</TreeViewItem.Header>
<TreeViewItem.ContextMenu>
<ContextMenu>
<MenuItem Header="删除" Click="MenuItem_Click_7"></MenuItem>
</ContextMenu>
</TreeViewItem.ContextMenu>
</TreeViewItem>
</TreeView>
<Grid Grid.Row="2" Grid.Column="1">
<Grid.RowDefinitions>
<RowDefinition Height="40"></RowDefinition>
<RowDefinition Height="40"></RowDefinition>
<RowDefinition></RowDefinition>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="100"></ColumnDefinition>
<ColumnDefinition Width="208*"></ColumnDefinition>
<ColumnDefinition Width="100"></ColumnDefinition>
</Grid.ColumnDefinitions>
<Label Name="MusName" Grid.ColumnSpan="3" VerticalContentAlignment="Center" HorizontalContentAlignment="Left" FontSize="20" Content="未播放歌曲"></Label>
<Label Name="NowTime" Grid.Row="1" Grid.Column="0" HorizontalContentAlignment="Right" FontSize="20" VerticalContentAlignment="Center">00:00</Label>
<Label Name="EndTime" Grid.Row="1" Grid.Column="2" HorizontalContentAlignment="Left" FontSize="20" VerticalContentAlignment="Center">00:00</Label>
<Border x:Name="bd" Grid.Column="1" Grid.Row="1" Height="14" Width="680" BorderThickness="1" BorderBrush="Black" Background="Gray" MouseLeftButtonDown="bd_MouseLeftButtonDown">
<Label Name="valueLb" Background="Green" Width="0" HorizontalAlignment="Left"></Label>
</Border>
<Grid Grid.Row="2" Grid.Column="1" Grid.ColumnSpan="2">
<Grid.RowDefinitions>
<RowDefinition Height="20"></RowDefinition>
<RowDefinition Height="20"></RowDefinition>
<RowDefinition></RowDefinition>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="83*"></ColumnDefinition>
<ColumnDefinition Width="224*"/>
<ColumnDefinition Width="80"></ColumnDefinition>
<ColumnDefinition Width="306*"></ColumnDefinition>
</Grid.ColumnDefinitions>
<Border x:Name="UpBtn" MouseEnter="UpBtn_MouseEnter" MouseLeave="UpBtn_MouseLeave" MouseLeftButtonDown="UpBtn_MouseLeftButtonDown" MouseLeftButtonUp="UpBtn_MouseLeftButtonUp" Width="50" Height="50" HorizontalAlignment="Right" VerticalAlignment="Top" Margin="-293,-49,326.2,0" RenderTransformOrigin="-2.988,0.268" >
<Border.Background>
<ImageBrush ImageSource="img/92.png"></ImageBrush>
</Border.Background>
</Border>
<Border x:Name="StartBtn" Tag="true" MouseEnter="UpBtn_MouseEnter" MouseLeave="UpBtn_MouseLeave" MouseLeftButtonDown="UpBtn_MouseLeftButtonDown" MouseLeftButtonUp="UpBtn_MouseLeftButtonUp" Width="50" Height="50" VerticalAlignment="Top" HorizontalAlignment="Right" Margin="-223,-49,256.2,0">
<Border.Background>
<ImageBrush ImageSource="img/开始.png"></ImageBrush>
</Border.Background>
</Border>
<Border x:Name="DownBtn" MouseEnter="UpBtn_MouseEnter" MouseLeave="UpBtn_MouseLeave" MouseLeftButtonDown="UpBtn_MouseLeftButtonDown" MouseLeftButtonUp="UpBtn_MouseLeftButtonUp" Width="50" Height="50" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="-151,-49,0,0" RenderTransformOrigin="0.9,0.672" >
<Border.Background>
<ImageBrush ImageSource="img/94.png"></ImageBrush>
</Border.Background>
</Border>
</Grid>
</Grid>
<Grid Grid.Row="1" Grid.Column="1">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="219*"/>
<ColumnDefinition Width="674*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition></RowDefinition>
<RowDefinition Height="40"></RowDefinition>
</Grid.RowDefinitions>
<Label Name="lbLrc" Grid.Row="1" HorizontalContentAlignment="Center" FontSize="25" Content="未找到对应歌词" Grid.ColumnSpan="2" Margin="0,0,-0.4,0"></Label>
</Grid>
<MediaElement x:Name="mediaElement" HorizontalAlignment="Left" Height="188" Margin="0,186.8,0,-231.6" Grid.Row="2" VerticalAlignment="Top" Width="250"/>
</Grid>
</Window>
XAML.cs页面
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Forms;
using System.IO;
using System.Windows.Threading;
using System.Text.RegularExpressions;
using System.Drawing;
namespace 音乐播放界面
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
System.Windows.Controls.Image img = new System.Windows.Controls.Image();
img.Source = new BitmapImage(new Uri(@"../../img/qiu.jfif", UriKind.RelativeOrAbsolute));
img.Stretch = Stretch.Fill;
ImageBrush brush = new ImageBrush();
brush.ImageSource = img.Source;
tre.Background = brush;
//图标路径
NotifyIcon notify = new NotifyIcon();
notify.Icon = new Icon("../../img/yin.ico");
notify.Text = "正在播放......";
notify.Visible = true;
notify.BalloonTipTitle = "音乐播放器";
notify.BalloonTipText = "欢迎使用...";
notify.ShowBalloonTip(2000);
System.Windows.Forms.MenuItem menu = new System.Windows.Forms.MenuItem("");
System.Windows.Forms.MenuItem exit = new System.Windows.Forms.MenuItem("退出音乐播放器");
exit.Click += Exit_Click;
System.Windows.Forms.MenuItem[] menus = new System.Windows.Forms.MenuItem[] { menu, exit };
notify.ContextMenu = new System.Windows.Forms.ContextMenu(menus);
}
private void Exit_Click(object sender, EventArgs e)
{
this.Close();
}
//判断如果文件路径不存在则创建
MediaPlayer player = new MediaPlayer();
string path = @"../../music/";
string lovepath = @"../../love/";
string lrcpath = @"../../lrcpath/";
string BGpath = @"../../BG/";
private void Window_Loaded(object sender, RoutedEventArgs e)
{
ShowOldMic(path, MusicList);
ShowOldMic(lovepath, love);
//设置进度条时间
mediaElement.LoadedBehavior = MediaState.Manual;
mediaElement.MediaOpened += MediaElement_MediaOpened;
timer.Interval = TimeSpan.FromMilliseconds(10);
timer.Tick += Timer_Tick;
}
//实例化一个lrcList来记录歌词
List<string> lrcList = new List<string>();
//双击打开音乐
private void ViewItem_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
TreeViewItem item = sender as TreeViewItem;
string muPath = path + item.Tag;
PlayMusic(muPath, out lrcList);
}
//获取播放时间
private void Timer_Tick(object sender, EventArgs e)
{
NowTime.Content = mediaElement.Position.ToString("hh':'mm':'ss");
double bl = 0;
if (mediaElement.NaturalDuration.HasTimeSpan)
{
bl = mediaElement.Position.TotalSeconds / mediaElement.NaturalDuration.TimeSpan.TotalSeconds;
}
if (bl >= 0.9999999)
{
timer.Stop();
}
valueLb.Width = bd.Width * bl;
SetChat();
}
private void SetChat()
{
for (int i = 0; i < lrcList.Count; i++)
{
double nowt = mediaElement.Position.TotalMilliseconds;//当前播放的时间
string geci = "";
double current = GetLrcTime(i, out geci);
if (i < lrcList.Count - 1)
{
double next = GetLrcTime(i + 1, out string str);
if (current <= nowt && nowt < next)
{
lbLrc.Content = geci;
return;
}
}
else
{
lbLrc.Content = geci;
}
}
}
/// <summary>
/// 获取当前这句歌词的时间,以毫秒形式运算
/// </summary>
/// <param name="v"></param>
/// <param name="str"></param>
/// <returns></returns>
private double GetLrcTime(int index, out string chat)
{
double time = 0;
chat = "";
string[] everyChat = lrcList[index].Split(new char[] { '[', ']' });
string pattern = @"^(\d{2}:){1,2}(\d{2}.\d{2})$";
if (Regex.IsMatch(everyChat[1], pattern))
{
chat = everyChat[2];
string t = everyChat[1];
if (everyChat[1].Length <= 8)
{
t = "00:" + everyChat[1];
}
TimeSpan ts;
if (TimeSpan.TryParse(t, out ts))
{
time = ts.TotalMilliseconds;//判断的歌词的时间
}
}
return time;
}
//结束时间
DispatcherTimer timer = new DispatcherTimer();//进度条时间
TimeSpan time;
private void MediaElement_MediaOpened(object sender, RoutedEventArgs e)
{
time = mediaElement.NaturalDuration.TimeSpan;
EndTime.Content = time.ToString("hh':'mm':'ss");
}
//显示原有音乐
private void ShowOldMic(string path, TreeViewItem MusicList)
{
//通过路径拿到文件夹
DirectoryInfo directory = new DirectoryInfo(path);
//拿到文件夹中的子文件
var filename = directory.GetFiles();
foreach (var item in filename)
{
bool isadd = false;
foreach (TreeViewItem it in MusicList.Items)
{
if (it.Tag.ToString() == item.ToString())
{
isadd = true;
}
}
if (!isadd)
{
string name = item.Name;
name = name.Substring(0, name.Length - 4);
TreeViewItem viewItem = new TreeViewItem();
viewItem.Header = name;
viewItem.Tag = item.Name.ToString();
MusicList.Items.Add(viewItem);
viewItem.MouseDoubleClick += ViewItem_MouseDoubleClick;
}
}
}
//string path = @"music";
//导入音乐
private void DR_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog dialog = new OpenFileDialog();
// 筛选器(Filter)筛选mp3格式和Wav格式
dialog.Filter = "(*.mp3,*.wav)|*.mp3;*.wav;";
// 可选多项(Multiselect)
dialog.Multiselect = true;
dialog.InitialDirectory = " C:\\";
DialogResult result = dialog.ShowDialog();
//文件多选
////之选音乐格式文件
if (result == System.Windows.Forms.DialogResult.OK)
{
//DrMusic(dialog.FileNames.ToList(), true);
string[] fileList = dialog.FileNames;
foreach (string item in fileList)
{
FileInfo info = new FileInfo(item);
bool ishave = false;
string oldpath = item.Substring(0, item.LastIndexOf('\\'));
string newpath = info.Name.Substring(0, info.Name.LastIndexOf('.')) + ".lrc";
FileInfo fileold = new FileInfo(oldpath + @"\\" + newpath);
FileInfo filelrc = new FileInfo(lrcpath + @"/" + newpath);
if (!filelrc.Exists)
{
if (fileold.Exists)
{
fileold.CopyTo(filelrc.FullName);
}
else
{
System.Windows.Forms.MessageBox.Show(info.Name.Substring(0, info.Name.LastIndexOf('.')) + "未能找到歌词文件");
}
}
foreach (TreeViewItem tree in MusicList.Items)
{
if (tree.Header.ToString() == info.Name)
{
ishave = true;
System.Windows.MessageBox.Show(tree.Header + "文件已经存在");
}
// }
if (!ishave)
{
TreeViewItem mus = new TreeViewItem();
string name = info.Name;
name = name.Substring(0, name.Length - 4);
mus.Header = name;
mus.Tag = info.Name;
info.CopyTo(path + info.Name, true);
mus.MouseDoubleClick += ViewItem_MouseDoubleClick;
MusicList.Items.Add(mus);
}
}
}
}
}
string paths = "";
//春
private void MenuItem_Click(object sender, RoutedEventArgs e)
{
paths = "../../img/chun.jfif";
bgimg(paths);
}
private void bgimg(string paths)
{
System.Windows.Controls.Image image = new System.Windows.Controls.Image();
image.Source = new BitmapImage(new Uri(paths, UriKind.Relative));
ImageBrush brush = new ImageBrush();
brush.ImageSource = image.Source;
bj.Background = brush;
}
//夏
private void MenuItem_Click_1(object sender, RoutedEventArgs e)
{
paths = "../../img/xia.jfif";
bgimg(paths);
}
//秋
private void MenuItem_Click_2(object sender, RoutedEventArgs e)
{
paths = "../../img/qiu.jfif";
bgimg(paths);
}
//冬
private void MenuItem_Click_3(object sender, RoutedEventArgs e)
{
paths = "../../img/dong.jfif";
bgimg(paths);
}
//退出
private void MenuItem_Click_4(object sender, RoutedEventArgs e)
{
this.Close();
}
//添加到我的喜欢
private void MenuItem_Click_5(object sender, RoutedEventArgs e)
{
// 拿到选中的项
try
{
var item = tre.SelectedItem;
TreeViewItem treeViewItem = item as TreeViewItem;
FileInfo file = new FileInfo(path + @"/" + treeViewItem.Tag);
file.CopyTo(lovepath + @"/" + treeViewItem.Tag);
ShowOldMic(lovepath, love);
}
catch
{
System.Windows.Forms.MessageBox.Show("文件存在");
}
}
//删除单个文件
private void DeleteFile(string path, TreeViewItem items)
{
player.Stop();
var tem = tre.SelectedItem;
TreeViewItem te = tem as TreeViewItem;
if (te.Name != items.Name)
{
FileInfo file = new FileInfo(path + @"/" + te.Tag);
file.Delete();
items.Items.Remove(tem);
}
else
{
System.Windows.Forms.MessageBox.Show("不能删除歌单");
}
}
//删除音乐库
private void MenuItem_Click_6(object sender, RoutedEventArgs e)
{
DeleteFile(path, MusicList);
}
//删除我喜欢
private void MenuItem_Click_7(object sender, RoutedEventArgs e)
{
DeleteFile(lovepath, love);
}
private void UpBtn_MouseEnter(object sender, System.Windows.Input.MouseEventArgs e)
{
Border img = sender as Border;
img.Width = img.Height = 52;
img.BorderThickness = new Thickness(1);
img.BorderBrush = System.Windows.Media.Brushes.Black;
}
private void UpBtn_MouseLeave(object sender, System.Windows.Input.MouseEventArgs e)
{
Border img = sender as Border;
img.Width = img.Height = 50;
img.BorderThickness = new Thickness(0);
}
ImageBrush brush;
//鼠标放下
private void UpBtn_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
Border img = sender as Border;
brush = img.Background as ImageBrush;
if (img.Name == "UpBtn")
{
img.Background = new ImageBrush(new BitmapImage(new Uri("../../img/93.png", UriKind.Relative)));
}
else if (img.Name == "StartBtn")
{
if (img.Tag.ToString() == "true")
{
img.Tag = "false";
mediaElement.Pause();
img.Background = new ImageBrush(new BitmapImage(new Uri("../../img/暂停.png", UriKind.Relative)));
}
else if (img.Tag.ToString() == "false")
{
mediaElement.Play();
img.Tag = "true";
img.Background = new ImageBrush(new BitmapImage(new Uri("../../img/开始.png", UriKind.Relative)));
}
}
else if (img.Name == "DownBtn")
{
img.Background = new ImageBrush(new BitmapImage(new Uri("../../img/95.png", UriKind.Relative)));
}
}
//鼠标抬起
private void UpBtn_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
Border img = sender as Border;
if (img.Name == "StartBtn")
{
return;
}
img.Background = brush;
}
//字体放大
private void MenuItem_Click_8(object sender, RoutedEventArgs e)
{
this.FontSize += 5;
}
//字体缩小
private void MenuItem_Click_9(object sender, RoutedEventArgs e)
{
this.FontSize -= 5;
}
//自定义背景
private void MenuItem_Click_10(object sender, RoutedEventArgs e)
{
System.Windows.Controls.MenuItem menu = sender as System.Windows.Controls.MenuItem;
switch (menu.Tag.ToString())
{
case "春":
BGimage("../../img/chun.jfif");
break;
case "夏":
BGimage("../../img/xia.jfif");
break;
case "秋":
BGimage("../../img/qiu.jfif");
break;
case "冬":
break;
BGimage("../../img/dong.jfif");
case "自定义":
OpenFileDialog openFile = new OpenFileDialog();
openFile.Filter = "(*.png,*.jpg,*.jpeg,*.bmp)|*.png;*.jpg;*.jpeg;*.bmp;";
openFile.Title = "请选择背景图片";
openFile.InitialDirectory = "E:\\图片素材";
DialogResult result = openFile.ShowDialog();
if (result == System.Windows.Forms.DialogResult.OK)
{
string backgroundpath = openFile.FileName;
BGimage(backgroundpath);
}
break;
}
}
//背景事件
private void BGimage(string BGpath)
{
System.Windows.Controls.Image image1 = new System.Windows.Controls.Image();
image1.Source = new BitmapImage(new Uri(BGpath, UriKind.RelativeOrAbsolute));
ImageBrush brush1 = new ImageBrush();
brush1.ImageSource = image1.Source;
bj.Background = brush1;
}
//清空播放列表
private void MenuItem_Click_11(object sender, RoutedEventArgs e)
{
MusicList.Items.Clear();
love.Items.Clear();
player.Stop();
}
//播放音乐
void PlayMusic(string muPath, out List<string> vs)
{
string musicChat = "";
FileInfo file = new FileInfo(muPath);
//获取歌词名称
string musicName = file.Name.Substring(0, file.Name.LastIndexOf('.'));
MusName.Content = musicName;
FileInfo info = new FileInfo(lrcpath + musicName + ".lrc");
//歌词存在
if (info.Exists)
{
StreamReader reader = new StreamReader(lrcpath + musicName + ".lrc", Encoding.Default);
musicChat = reader.ReadToEnd();
}
//歌词换行
vs = musicChat.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries).ToList();
timer.Start();
mediaElement.Source = new Uri(muPath, UriKind.Relative);
mediaElement.Play();
}
//进度条点击
private void bd_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
System.Windows.Point point = e.GetPosition(bd);
mediaElement.Clock = null;
string[] points = point.ToString().Split(',');
double jindu = double.Parse((Convert.ToDouble(points[0]) / bd.Width).ToString("0.00"));
mediaElement.Position = new TimeSpan(0, 0, 0, 0, (int)(jindu * time.TotalMilliseconds));
}
}
}