你顺利加入了一家初创软件公司,该公司需要为客户开发一款音乐播放软件。软件部经理决定将歌词文件显示的功能交给你完成,结合桌面应用程序开发所学知识,顺利完成上述软件的开发工作。最终效果见Demo文件夹:
-
lrc文件介绍:lrc文件存放的即为每首歌曲对应的歌词,已文本文件的方式存储。所以,你可以利用记事本程序打开上述文件进行查看。
-
打开素材文件夹中的“陈一发儿-童话镇.lrc”,具体内容如下,其中[]以内的内容为该条歌词应该出现的时间,例如第一句歌词出现在:00分,22.78秒。
-
软件需求及编码提示:
该软件只需要一个窗体,该窗体名称为FrmKuwoMusic, 该窗体标题为“酷我音乐盒”, 窗体大小为800*600,窗体边框类型固定,即不让用户改变窗体的大小。
在该窗体的左下角,放置一个按钮,按钮标题为:“载入歌词”。
当用户点击“载入歌词”菜单后,通过OpenFileDialog对象,载入某个lrc文件。通过OpenFileDialog对象的ShowDialog()方法显示文件打开对话框,通过OpenFileDialog对象的FileName属性可以获得用户希望载入的lrc文件名。
获得了lrc文件名称后,即可通过StreamReader对象的readLine( ),读入lrc文件中的所有歌词,存放在List中。注意:利用string类提供的subString( )方法,移除每行歌词前面的时间戳,只保留实际歌词内容。如果读取的文件显示为乱码,请在构建StreamReader对象的时候,加入解码参数,如下:
通过for循环,遍历存放歌词的List链表。每个循环中,创建一个Label,通过设置Label的Location,以及Text属性,可以为每一个Label控件设置对应的坐标位置以及歌词内容。注意:每个Label歌词的x坐标为100,y坐标每行歌词增加20。然后利用this.Controls.add()将新建的Label添加到窗体上加以显示。
代码部分:
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.IO;
namespace practice12
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
/*class lyricline
{
private int minute;
public int Minute
{
get { return minute; }
set { minute = value; }
}
private double second;
public double Second
{
get { return second; }
set { second = value; }
}
private string strLyric;
public string StrLyric
{
get { return strLyric; }
set { strLyric = value; }
}
Label lblLyric;
public Label LblLyric
{
get { return lblLyric; }
set { lblLyric = value; }
}
}*/
private void Form1_Load(object sender, EventArgs e)
{
}
int ypos = 20;
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog file = new OpenFileDialog();
file.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
file.Filter = "(lrc文件)*lrc|*.lrc";
file.Title = "请选择歌词文件";
if (file.ShowDialog() == DialogResult.OK)
{
FileStream fs = new FileStream(file.FileName, FileMode.Open);
StreamReader sr = new StreamReader(fs,Encoding.Default);
List<string> lrclst = new List<string>();
string s;
while ((s = sr.ReadLine() )!= null)
{
if (s.Equals(""))
{
continue;
}
else
{
lrclst.Add(s.Substring(10));
}
}
for(int i=0;i<lrclst.Count;i++)
{
Label lelLyric = new Label();
lelLyric.Text = lrclst[i];
lelLyric.Location = new Point(100, ypos);
ypos += 40;
lelLyric.BackColor = Color.Transparent;
lelLyric.Width = 600;
lelLyric.Height = 40;
lelLyric.Font = new Font("微软雅黑", 20);
lelLyric.ForeColor = Color.Black;
this.Controls.Add(lelLyric);
}
}
}
}
}
运行结果: