wpf 音乐盒制作二(歌词滚动)

来源:互联网 发布:js怎么给input赋值 编辑:程序博客网 时间:2024/06/05 05:04
 终于把歌词搞定了,先说说逻辑吧,当加载每一首歌的时候都需要用正则表达式去判断歌词,如果存在则进行时间段取词保存,当需要播放或者列表循环,单曲播放等只要是自动播放或者手动点击加载歌曲是就需要去获取列表中的歌词数值,如果为零则无歌词,如果不为零则加载歌词,显示使用的事textblock,需要出现滚动效果的话就需要匹配时间,根据时间戳去获取歌词,然后向上滚动歌词。上图贴码了:
不过今天晚上对以前的进行了优化,把menu改成了tabcontrol,因为nemu不方面各种功能的实现,把tabcontrol的边框消隐,查了好久才查到这个属性。
不多说了看效果: 
 
 
前台界面
  <Grid >
                        <Canvas  Background="Transparent" >
                            <Image Source="/MyMusic;component/Images/jun.jpg" Width="396" VerticalAlignment="Stretch" Height="210" Opacity="0.3" Canvas.Left="-12" Canvas.Top="0">
                               
                            </Image>
                            <TextBlock Canvas.Left="6" Canvas.Top="225" Height="33" Name="textBlock2" Text="" Width="378" Background="Transparent" TextAlignment="Center" FontWeight="Bold" FontStyle="Italic" FontSize="13" Foreground="Red"><TextBlock.OpacityMask><LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0"><GradientStop Color="#78DD3E27" Offset="0.041" /><GradientStop Color="Black" Offset="0.976" /></LinearGradientBrush></TextBlock.OpacityMask></TextBlock>
                            <TextBlock Canvas.Left="6" Canvas.Top="273" Height="32" Name="textBlock3" Text="" Width="378" Background="Transparent" FontWeight="Bold" FontStyle="Italic" TextAlignment="Center" FontSize="13"><TextBlock.Foreground><LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0"><GradientStop Color="Red" Offset="0.081" /><GradientStop Color="#7FFF0005" Offset="0.878" /></LinearGradientBrush></TextBlock.Foreground></TextBlock>
                            <TextBlock Canvas.Left="6" Canvas.Top="311" Height="45" Name="textBlock4" Text="" Width="378" Background="Transparent" FontSize="15" TextAlignment="Center" FontStyle="Italic" FontWeight="Bold" Foreground="#FFFFD000"></TextBlock>
                            <TextBlock Canvas.Left="6" Canvas.Top="362" Height="38" Name="textBlock5" Text="" Width="378" Background="Transparent" FontSize="13" FontStyle="Italic" FontWeight="Bold" TextAlignment="Center"><TextBlock.Foreground><LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0"><GradientStop Color="White" Offset="0" /><GradientStop Color="#FFDA0020" Offset="1" /></LinearGradientBrush></TextBlock.Foreground></TextBlock>
                            <TextBlock Canvas.Left="0" Canvas.Top="406" Height="40" Name="textBlock6" Text="" Width="384" Background="Transparent" FontSize="13" TextAlignment="Center" FontStyle="Italic" FontWeight="Bold"><TextBlock.Foreground><LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0"><GradientStop Color="NavajoWhite" Offset="0.016" /><GradientStop Color="Red" Offset="1" /></LinearGradientBrush></TextBlock.Foreground></TextBlock>
                        </Canvas>
                    </Grid>
后台代码
通过获取歌词和对应的时间保存在结果体中
  //读取lrc文件  
        private void ReadLyric(ref finfo f, string filelyric)
        {
            string lrc = File.ReadAllText(filelyric, System.Text.Encoding.GetEncoding("GB2312"));
            Regex rx = new Regex(@"(?<=^\[)(\d+:\d+\.\d+).(.+)(?=$)", RegexOptions.Multiline);
            //匹配表达式  
            foreach (Match x in rx.Matches(lrc))
            {
                try
                {
                    //读取时间  
                    TimeSpan ti = new TimeSpan(0, int.Parse(x.Value.Substring(0, 2)),
                                            int.Parse(x.Value.Substring(3, 2)));//int.Parse(x.Value.Substring(6, 2))  
                    //读取歌词  
                    string ly = x.Value.Substring(9);
                    f.Lyric.Add(new lyricinfo() { time = ti, lrc = ly });
                }
                catch
                {
                    //continue;  
                }
            }
            //保存歌词文件
            SaveLyric(f.Filename, filelyric);
        } 
将歌词路径保存在对应的歌路径文件中
   /// <summary>
        /// 保存歌词路径
        /// </summary>
        /// <param name="filelyric"></param>
        private void  SaveLyric(string name, string filelyric)
        {
            string n = name.Remove(name.Length - 4);
            if (Directory.Exists(filepath))
            {
                byte[] pathbyte = Encoding.Unicode.GetBytes(filelyric);
                FileStream myStream = new FileStream(filepath + n + ".lrc", FileMode.Create);
                StreamWriter sw = new StreamWriter(myStream, Encoding.Default);
                sw.Write(filelyric);
                sw.Close();
                myStream.Close();

            }
            else
            {
                Directory.CreateDirectory(filepath);
                byte[] pathbyte = Encoding.Unicode.GetBytes(filelyric);
                FileStream myStream = new FileStream(filepath + n + ".lrc", FileMode.Create);
                StreamWriter sw = new StreamWriter(myStream, Encoding.Default);
                sw.Write(filelyric);
                sw.Close();
                myStream.Close();
            }
        }
图片 
每次启动会自动加载歌曲加载歌词,代码
  /// <summary>
        /// 加载歌曲名称
        /// </summary>
        private void Loadmusic()
        {
            ///如果存在文件读取
            if (Directory.Exists(filepath))
            {
                string[] fileNames = Directory.GetFiles(filepath);

                for (int i = 0; i < fileNames.Length; i++)
                {
                    string a = fileNames[i].Substring(fileNames[i].Length - 3, 3);
                    if (fileNames[i].Substring(fileNames[i].Length - 3, 3) == "fsf")
                    {
                        FileStream mystream = new FileStream(fileNames[i], FileMode.Open, FileAccess.Read);
                        StreamReader sr = new StreamReader(mystream, Encoding.Default);
                        string data = sr.ReadToEnd();
                        sr.Close();
                        mystream.Close();
                        string lastname = data.Remove(data.Length - 4);
                        finfo newfile = new finfo(lastname.Substring(lastname.LastIndexOf("\\") + 1), data);
                        for (int j = 0; j < fileNames.Length; j++)
                        {
                            if (fileNames[j].Substring(fileNames[j].Length - 3, 3) == "lrc"&&fileNames[j].Remove(fileNames[j].Length-4)==fileNames[i].Remove(fileNames[i].Length-4))
                            {
                                FileStream stream = new FileStream(fileNames[j], FileMode.Open, FileAccess.Read);
                                StreamReader s = new StreamReader(stream, Encoding.Default);
                                string da = s.ReadToEnd();
                                sr.Close();
                                mystream.Close();
                                LoadLyric(ref newfile, da);
                            }
                        }
                        list.Add(newfile);
                    }
                   
                }
                listbox.Items.Clear();
                if (list.Count > 0)
                {
                    for (int j = 0; j < list.Count; j++)
                    {
                        listbox.Items.Add(list[j].Filename);
                    }
                    itemlist.ExpandSubtree();
                    listbox.SelectedIndex = listbox.Items.Count - 1;
                }
                startbtn.Content = "开始";
            }
            myplayer.MediaOpened += new RoutedEventHandler(myplayer_MediaOpened);
            myplayer.Pause();
        }
        //读取lrc文件  
        private void LoadLyric(ref finfo f, string filelyric)
        {
            string lrc = File.ReadAllText(filelyric, System.Text.Encoding.GetEncoding("GB2312"));
            Regex rx = new Regex(@"(?<=^\[)(\d+:\d+\.\d+).(.+)(?=$)", RegexOptions.Multiline);
            //匹配表达式  
            foreach (Match x in rx.Matches(lrc))
            {
                try
                {
                    //读取时间  
                    TimeSpan ti = new TimeSpan(0, int.Parse(x.Value.Substring(0, 2)),
                                            int.Parse(x.Value.Substring(3, 2)));//int.Parse(x.Value.Substring(6, 2))  
                    //读取歌词  
                    string ly = x.Value.Substring(9);
                    f.Lyric.Add(new lyricinfo() { time = ti, lrc = ly });
                }
                catch
                {
                    //continue;  
                }
            }
        } 
歌词滚动更新还是采用了     myplayer_MediaOpened(object sender, RoutedEventArgs e)中的timer_Tick

 主要代码在此,其他就不罗嗦了,下面实现歌词下载:
图片 
界面还没有搭建,只是搞完了后台代码实现: 
  class MusicAPI
    {
        #region 实体类
        /// <summary>
        /// 搜搜音乐实体类
        /// </summary>
        public class SouSouMusic
        {
            /// <summary>
            /// 歌曲名字
            /// </summary>
            public string name { get; set; }
            /// <summary>
            /// 歌曲mp3路径
            /// </summary>
            public List<string> mp3path { get; set; }
            /// <summary>
            /// 歌曲wma路径
            /// </summary>
            public List<string> wmapath { get; set; }
            /// <summary>
            /// 歌曲作者
            /// </summary>
            public string by { get; set; }
        }
        #endregion

        #region 音乐搜索接口
        /// <summary>
        /// 搜搜接口
        /// </summary>
        /// <param name="KeyWord">关键字</param>
        /// <param name="page">i=1,返回20条数据,i=2,返回40条</param>
        /// 正则学的不好。Substring处理的数据,可以自行修改
        public static List<SouSouMusic> SouSouSearch(string KeyWord, int pageindex)
        {
            List<SouSouMusic> list = new List<SouSouMusic>();

            for (int id = 1; id <= pageindex; id++)
            {
                #region 数据处理
                try
                {
                    string strAPI = "http://cgi.music.soso.com/fcgi-bin/m.q?w=";
                    strAPI = strAPI + UrlEncode(KeyWord);//关键字编码转换
                    strAPI = strAPI + "&p=" + id;
                    Uri url = new Uri(strAPI);
                    WebClient MyWebClient = new WebClient();
                    string Web = MyWebClient.DownloadString(url);
                    while (Web.IndexOf("<td class=\"data\">") >= 0)
                    {
                        string Web1 = Web.Substring(Web.IndexOf("<td class=\"data\">") + 17, Web.Length - 18 - Web.IndexOf("<td class=\"data\">"));
                        //当前歌曲所以信息
                        string Web2 = Web1.Substring(0, Web1.IndexOf("</td>"));
                        Web = Web1;
                        int i = Web2.IndexOf("@@");
                        //音乐名字
                        string MusicName = Web2.Substring(Web2.IndexOf("@@") + 2, Web2.Length - Web2.IndexOf("@@") - 5);
                        MusicName = MusicName.Substring(0, MusicName.IndexOf("@@"));
                        //作者名字
                        string use = Web2.Substring(Web2.IndexOf("@@") + 2, Web2.Length - Web2.IndexOf("@@") - 3);
                        use = use.Substring(use.IndexOf("@@") + 2, use.Length - use.IndexOf("@@") - 3);
                        use = use.Substring(use.IndexOf("@@") + 2, use.Length - use.IndexOf("@@") - 3);
                        use = use.Substring(0, use.IndexOf("@@"));
                        //歌曲连接 分为MP3 和 WMA 
                        List<string> mp3path = new List<string>();
                        List<string> wmapath = new List<string>();
                        try
                        {
                            while (Web2.IndexOf("@@FI") >= 0)
                            {
                                string path = Web2.Substring(Web2.IndexOf("@@FI") + 4, Web2.Length - Web2.IndexOf("@@FI") - 4);
                                Web2 = path;
                                path = path.Substring(0, path.IndexOf(".wma") + 4);
                                wmapath.Add(path);
                            }
                            while (Web2.IndexOf("SI") >= 0)
                            {
                                string path = Web2.Substring(Web2.IndexOf("SI") + 2, Web2.Length - Web2.IndexOf("SI") - 2);
                                Web2 = path;
                                path = path.Substring(0, path.IndexOf(".mp3") + 4);
                                mp3path.Add(path);
                            }
                        }
                        catch (Exception)
                        {

                        }
                        //int s = Web2.IndexOf("@@FI");
                        // int d = Web2.IndexOf(".wma");
                        SouSouMusic so = new SouSouMusic();
                        so.name = MusicName.Replace("@", "");
                        so.by = use.Replace("@", "");
                        so.mp3path = mp3path;
                        so.wmapath = wmapath;
                        list.Add(so);
                    }
                }
                catch (WebException)
                {

                }
                #endregion
            }
            return list;


        }
        #endregion

        #region 字符编码转化
        /// <summary>
        /// //字符编码转化
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string UrlEncode(string str)
        {
            StringBuilder sb = new StringBuilder();
            byte[] byStr = System.Text.Encoding.Default.GetBytes(str);
            for (int i = 0; i < byStr.Length; i++)
            {
                sb.Append(@"%" + Convert.ToString(byStr[i], 16));
            } return (sb.ToString());
        }
        #endregion

        #region 音乐下载
        /// <summary>
        /// 下载音乐
        /// </summary>
        /// <param name="DownUrl"></param>
        /// <param name="SavePath"></param>
        /// <returns></returns>
        public static bool DownMusic(string DownUrl, string SavePath)
        {

            try
            {
                Thread th = new Thread(new ParameterizedThreadStart(Down));
                DownFileInfo d = new DownFileInfo(DownUrl, SavePath);
                th.IsBackground = true;
                th.Start(d);
            }
            catch (Exception)
            {
                return false;
            }

            return true;
        }
        /// <summary>
        /// 线程
        /// </summary>
        private static void Down(object obj)
        {
            DownFileInfo d = (DownFileInfo)obj;
            WebClient wb = new WebClient();
            wb.DownloadFile(d.DownUrl, d.SavePath);
        }
        /// <summary>
        /// 下载文件属性类
        /// </summary>
        public class DownFileInfo : Object
        {
            public DownFileInfo(string DownUrl, string SavePath)
            {
                this.SavePath = SavePath;
                this.DownUrl = DownUrl;
            }
            public string SavePath { get; set; }
            public string DownUrl { get; set; }
        }

        #endregion
    }

效果争取明天晚上搞出来,哈哈,不早了,睡觉。 
0 0
原创粉丝点击