Tải lyric và bài hát app nghe nhạc MP3

App nghe nhạc MP3 crawl data từ mp3.zing.vn

5.0 (1 đánh giá)
Tạo bởi Kteam Cập nhật lần cuối 16:49 03-01-2019 3.780 lượt xem 7 bình luận
Học nhanh

Danh sách bài học

Tải lyric và bài hát app nghe nhạc MP3

Chúng ta cùng nhau tìm hiểu cách để làm ra một app nghe nhạc nhé.

 

MainStyle.xaml

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:local="clr-namespace:MusicAppMP3">
    <Style TargetType="TextBlock">
        <Setter Property="HorizontalAlignment" Value="Center"></Setter>
        <Setter Property="VerticalAlignment" Value="Center"></Setter>
    </Style>
</ResourceDictionary>

 

MainWindow.xaml

<Window x:Class="MusicAppMP3.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:uc="clr-namespace:MusicAppMP3"
        xmlns:local="clr-namespace:MusicAppMP3"
        mc:Ignorable="d"
        WindowStartupLocation="CenterScreen"
        FontFamily="Arial"
        Title="MainWindow" Height="650" Width="525">
    <Window.Resources>
        <ResourceDictionary Source="MainStyle.xaml"></ResourceDictionary>
    </Window.Resources>
    <Grid>
        <Grid x:Name="gridTop10">
            <Grid.RowDefinitions>
                <RowDefinition Height="auto"></RowDefinition>
                <RowDefinition></RowDefinition>
            </Grid.RowDefinitions>

            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition></ColumnDefinition>
                    <ColumnDefinition></ColumnDefinition>
                    <ColumnDefinition></ColumnDefinition>
                </Grid.ColumnDefinitions>

                <Grid Grid.Column="0">
                    <ToggleButton IsChecked="{Binding IsCheckVN}">BXH Việt Nam</ToggleButton>
                </Grid>
                <Grid Grid.Column="1">
                    <ToggleButton IsChecked="{Binding IsCheckEU}">BXH Âu Mỹ</ToggleButton>
                </Grid>
                <Grid Grid.Column="2">
                    <ToggleButton IsChecked="{Binding IsCheckKO}">BXH Hàn Quốc</ToggleButton>
                </Grid>
            </Grid>

            <Grid Grid.Row="1">
                <ListBox x:Name="lsbTopSongs" HorizontalContentAlignment="Stretch">
                    <ListBox.ItemTemplate>
                        <DataTemplate>
                            <Border VerticalAlignment="Stretch" Height="50" BorderThickness="2" BorderBrush="Black">
                                <Grid>
                                    <Grid.ColumnDefinitions>
                                        <ColumnDefinition Width="50"></ColumnDefinition>
                                        <ColumnDefinition></ColumnDefinition>
                                        <ColumnDefinition Width="50"></ColumnDefinition>
                                    </Grid.ColumnDefinitions>

                                    <Grid>
                                        <TextBlock HorizontalAlignment="Center" 
                               VerticalAlignment="Center">01</TextBlock>
                                    </Grid>

                                    <Grid Grid.Column="1">
                                        <Grid.RowDefinitions>
                                            <RowDefinition></RowDefinition>
                                            <RowDefinition></RowDefinition>
                                        </Grid.RowDefinitions>

                                        <Grid>
                                            <TextBlock HorizontalAlignment="Left" Text="{Binding SongName}"></TextBlock>
                                        </Grid>

                                        <Grid Grid.Row="1">
                                            <TextBlock HorizontalAlignment="Left">Tên ca sỹ</TextBlock>
                                        </Grid>
                                    </Grid>

                                    <Grid Grid.Column="2">
                                        <Button Click="Button_Click">Play</Button>
                                    </Grid>
                                </Grid>
                            </Border>
                        </DataTemplate>
                    </ListBox.ItemTemplate>
                </ListBox>
            </Grid>
        </Grid>
        <uc:SongInfoUC x:Name="ucSongInfo" Visibility="Hidden"></uc:SongInfoUC>
    </Grid>    
</Window>

 

MainWindow.cs

using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
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 xNet;

namespace MusicAppMP3
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window, INotifyPropertyChanged
    {
        private bool isCheckVN;
        private bool isCheckEU;
        private bool isCheckKO;
        private ObservableCollection<Song> listVN;
        private ObservableCollection<Song> listEU;
        private ObservableCollection<Song> listKO;
        public bool IsCheckVN { get => isCheckVN; set { isCheckVN = value; lsbTopSongs.ItemsSource = ListVN; isCheckEU = false; isCheckKO = false; OnPropertyChanged("IsCheckVN"); OnPropertyChanged("IsCheckEU"); OnPropertyChanged("IsCheckKO"); } }
        public bool IsCheckEU { get => isCheckEU; set { isCheckEU = value; lsbTopSongs.ItemsSource = ListEU; isCheckVN = false; isCheckKO = false; OnPropertyChanged("IsCheckVN"); OnPropertyChanged("IsCheckEU"); OnPropertyChanged("IsCheckKO"); } }
        public bool IsCheckKO { get => isCheckKO; set { isCheckKO = value; lsbTopSongs.ItemsSource = ListKO; isCheckEU = false; isCheckVN = false; OnPropertyChanged("IsCheckVN"); OnPropertyChanged("IsCheckEU"); OnPropertyChanged("IsCheckKO"); } }

        public ObservableCollection<Song> ListVN { get => listVN; set => listVN = value; }
        public ObservableCollection<Song> ListEU { get => listEU; set => listEU = value; }
        public ObservableCollection<Song> ListKO { get => listKO; set => listKO = value; }

        public MainWindow()
        {
            InitializeComponent();
            ucSongInfo.BackToMain += UcSongInfo_BackToMain;            

            this.DataContext = this;
            
            ListVN = new ObservableCollection<Song>();
            ListEU = new ObservableCollection<Song>();
            ListKO = new ObservableCollection<Song>();
            CrawlBXH();
            IsCheckVN = true;
        }      

        void CrawlBXH()
        {           
            HttpRequest http = new HttpRequest();
            string htmlBXH = http.Get(@"http://mp3.zing.vn/bang-xep-hang/index.html").ToString();            
            string bxhPattern = @"<div class=""box-chart-ov bordered non-bg-rank"">(.*?)</ul>";
            var listBXH = Regex.Matches(htmlBXH, bxhPattern, RegexOptions.Singleline);

            string bxhVN = listBXH[0].ToString();
            AddSongToListSong(ListVN, bxhVN);

            string bxhEU = listBXH[1].ToString();
            AddSongToListSong(ListEU, bxhEU);

            string bxhKO = listBXH[2].ToString();
            AddSongToListSong(ListKO, bxhKO);

        }

        void AddSongToListSong(ObservableCollection<Song> listSong, string html)
        {
            var listSongHTML = Regex.Matches(html, @"<li>(.*?)</li>", RegexOptions.Singleline);
            for (int i = 0; i < listSongHTML.Count; i++)
            {
                var songandsinger = Regex.Matches(listSongHTML[i].ToString(), @"<a\s\S*\stitle=""(.*?)""", RegexOptions.Singleline);

                string songString = songandsinger[0].ToString();
                int indexSong = songString.IndexOf("title=\"");
                string songName = songString.Substring(indexSong, songString.Length - indexSong - 1).Replace("title=\"", "");

                string singerString = songandsinger[1].ToString();
                int indexSinger = singerString.IndexOf("title=\"");
                string singerName = singerString.Substring(indexSinger, singerString.Length - indexSinger - 1).Replace("title=\"", "");

                int indexURL = songString.IndexOf("href="/redirect?Id=QISDLP572qPnk7xClCPxIw%3d%3d"
                string URL = songString.Substring(indexURL, indexSong - indexURL - 2).Replace("href="/redirect?Id=WeUvSTDVE8l2DW8fweMYdQ%3d%3d" "");

                HttpRequest http = new HttpRequest();
                string htmlSong = http.Get(@"http://mp3.zing.vn" + URL).ToString();

                var lirycs = Regex.Matches(htmlSong, @"<p class=""fn-wlyrics fn-content""(.*?)</p>", RegexOptions.Singleline);
                string tempLiryc = "Chưa có lyric";
                if (lirycs.Count > 0)
                {
                    tempLiryc = lirycs[0].ToString();
                    string tempToCut = tempLiryc.Substring(0, tempLiryc.IndexOf('>') + 1);
                    tempLiryc = tempLiryc.Replace(tempToCut, "").Replace("<br>", "").Replace("</p>", "");
                }

                string getJsonURL = Regex.Match(htmlSong, @"<div id=""zplayerjs-wrapper"" class=""player"" data-xml=""(.*?)""", RegexOptions.Singleline).Value.Replace(@"<div id=""zplayerjs-wrapper"" class=""player"" data-xml=""", "").Replace("\"","");
                string jsonInfo = http.Get(@"http://mp3.zing.vn" + getJsonURL).ToString();
                JObject jObject = JObject.Parse(jsonInfo);

                string name = jObject["data"][0]["name"].ToString();

                string downloadURL = jObject["data"][0]["source_list"].ToString();
                downloadURL = downloadURL.Substring(downloadURL.IndexOf("http"), downloadURL.IndexOf(",") - downloadURL.IndexOf("http") - 1);
                string photoURL = jObject["data"][0]["cover"].ToString();


                listSong.Add(new Song() { SingerName = singerName, SongName = songName, SongURL = URL, STT = i + 1, Lyric=tempLiryc, DownloadURL=downloadURL, PhotoURL = photoURL });
            }
        }        

        private void UcSongInfo_BackToMain(object sender, EventArgs e)
        {
            gridTop10.Visibility = Visibility.Visible;
            ucSongInfo.Visibility = Visibility.Hidden;
        }
        
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            Song song = (sender as Button).DataContext as Song;
            
            gridTop10.Visibility = Visibility.Hidden;
            ucSongInfo.Visibility = Visibility.Visible;
            ucSongInfo.SongInfo = song;
        }

        public event PropertyChangedEventHandler PropertyChanged;
        protected virtual void OnPropertyChanged(string newName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(newName));
            }
        }
    }
}

 

SongInfoUC.xaml

<UserControl x:Class="MusicAppMP3.SongInfoUC"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:local="clr-namespace:MusicAppMP3"
             mc:Ignorable="d" >
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="auto"></RowDefinition>
            <RowDefinition Height="200"></RowDefinition>
            <RowDefinition></RowDefinition>
        </Grid.RowDefinitions>

        <Grid>
            <Button Click="Button_Click">Back</Button>
        </Grid>

        <Grid Grid.Row="1">
            <Button>Play song</Button>
        </Grid>

        <Grid Grid.Row="2">
            <TextBlock>Lyric</TextBlock>
        </Grid>
    </Grid>
</UserControl>

 

SongInfoUC.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
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;

namespace MusicAppMP3
{
    /// <summary>
    /// Interaction logic for SongInfoUC.xaml
    /// </summary>
    public partial class SongInfoUC : UserControl
    {
        private Song songInfo;
        public Song SongInfo { get { return songInfo; } set { songInfo = value; DownloadSong(SongInfo); } }
        public SongInfoUC()
        {
            InitializeComponent();
        }

        private event EventHandler backToMain;
        public event EventHandler BackToMain
        {
            add { backToMain += value; }
            remove { backToMain -= value; }
        }

        void DownloadSong(Song songInfo)
        {
            WebClient wb = new WebClient();
            wb.DownloadFile(SongInfo.DownloadURL, AppDomain.CurrentDomain.BaseDirectory + "Song\\" + songInfo.SongName + ".mp3");
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            if (backToMain != null)
                backToMain(this, new EventArgs());
        }
    }
}

 

Song.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MusicAppMP3
{
    public class Song
    {
        private string songName;
        private string singerName;
        private string songURL;
        private int sTT;
        private string lyric;
        private string downloadURL;
        private string photoURL;

        public string SongName { get => songName; set => songName = value; }
        public string SingerName { get => singerName; set => singerName = value; }
        public string SongURL { get => songURL; set => songURL = value; }
        public int STT { get => sTT; set => sTT = value; }
        public string Lyric { get => lyric; set => lyric = value; }
        public string DownloadURL { get => downloadURL; set => downloadURL = value; }
        public string PhotoURL { get => photoURL; set => photoURL = value; }
    }
}

 

Download full project

xNet

Reg Test


Thảo luận

Nếu bạn có bất kỳ khó khăn hay thắc mắc gì về khóa học, đừng ngần ngại đặt câu hỏi trong phần BÌNH LUẬN bên dưới hoặc trong mục HỎI & ĐÁP trên thư viện Howkteam.com để nhận được sự hỗ trợ từ cộng đồng.

Nội dung bài viết

Tác giả

Khóa học

App nghe nhạc MP3 crawl data từ mp3.zing.vn

App nghe nhạc MP3 crawl data từ mp3.zing.vn

Đánh giá

nucasspro đã đánh giá 19:38 01-03-2019

Bình luận

Để bình luận, bạn cần đăng nhập bằng tài khoản Howkteam.

Đăng nhập
Lmq đã bình luận 17:24 15-12-2018

test commnet

phamngocson.l13cla đã bình luận 23:10 31-05-2018

mong là sớm 100

 

stevenjobs1996 đã bình luận 13:34 25-03-2018

hy vọng đủ điểm để xem dc bài viết,, Đạt Quốc

Nguyễn Trung Hiếu đã bình luận 03:13 23-06-2017

string getJSonURL = Regex.Match(htmlSong, @"<div id=""zplayerjs-wrapper"" class=""player"" data-xml=""(.*?)""",      RegexOptions.Singleline).Value.Replace(@"<div id=""zplayerjs-wrapper"" class=""player"" data-xml=""", "").Replace("\"", "");
string jsonInfo = http.Get(@"http://mp3.zing.vn" + getJSonURL).ToString();

Cho em hỏi sao jsonInfo nó lại mang giá trị null trong khi getJSonURL vẫn có giá trị
 

Không có video.