Ejemplo n.º 1
0
 /// <summary>
 /// 获取歌曲封面图片
 /// </summary>
 /// <param name="path">歌曲文件路径</param>
 /// <returns>图片文件</returns>
 public static BitmapImage GetAlbumCover(string path)
 {
     if (path != null)
     {
         try
         {
             ID3Info     info          = new ID3Info(path, true);
             var         pictureFrames = info.ID3v2Info.AttachedPictureFrames.Items;
             BitmapImage bitmapImage   = new BitmapImage();
             if (pictureFrames.Any())
             {
                 AttachedPictureFrame ap = info.ID3v2Info.AttachedPictureFrames.Items[0];
                 bitmapImage.BeginInit();
                 bitmapImage.StreamSource = ap.Data;
                 bitmapImage.EndInit();
             }
             else
             {
                 bitmapImage = new BitmapImage(new Uri(@"/Player4;component/Image/DefaultImage.png", UriKind.RelativeOrAbsolute));
             }
             return(bitmapImage);
         }
         catch (Exception e)
         {
             MessageBox.Show(e.Message);
             return(null);
         }
     }
     return(null);
 }
Ejemplo n.º 2
0
        public listMusicItem(string path, string bg, string outpath)
        {
            this.path = path;
            updatePaths(bg, outpath);

            // get ze id3 dataz!
            // http://www.codeproject.com/KB/cs/Do_Anything_With_ID3.aspx
            ID3Info f   = new ID3Info(path, true);
            ID3v2   id3 = f.ID3v2Info;

            this.title  = id3.GetTextFrame("TIT2");
            this.artist = id3.GetTextFrame("TPE1");
            this.album  = id3.GetTextFrame("TALB");

            Console.WriteLine("------ File ID3 data :: " + Path.GetFileName(path));
            Console.WriteLine("Title: " + title);
            Console.WriteLine("Artist: " + artist);
            Console.WriteLine("Album: " + album);

            // try to get any images if possible
            images = new Image[id3.AttachedPictureFrames.Count];
            for (int i = 0; i < id3.AttachedPictureFrames.Count; i++)
            {
                AttachedPictureFrame ap = id3.AttachedPictureFrames.Items[i];

                // Empty catch!? :o SHOCK! HORROR! no seriously, who cares what goes wrong here...
                try { images[i] = Image.FromStream(ap.Data); } catch { }
            }

            Console.WriteLine("Images Found: " + images.Length.ToString());
        }
            /// <summary>
            /// Read Image Cover from ID3 audio tag
            /// Feature is supported in version 18.2 or greater of the API
            /// </summary>
            public static void ReadImageCoverID3()
            {
                try
                {
                    // init Mp3Format class
                    using (Mp3Format mp3Format = new Mp3Format(Common.MapSourceFilePath(filePath)))
                    {
                        // get id3v2
                        var metadata = mp3Format.GetId3v2Tag();

                        // check if ID3v2 is exist
                        if (metadata == null)
                        {
                            return;
                        }

                        // read APIC frames
                        var frames = metadata["APIC"];

                        if (frames != null && frames.Length == 1)
                        {
                            // get AttachedPictureFrame
                            AttachedPictureFrame picture = (AttachedPictureFrame)frames[0];

                            // use 'jpeg' as default extension
                            string extension = ".jpeg";
                            string mimeType  = picture.MIMEType;

                            // try resolve extension from MIME
                            if (mimeType != null)
                            {
                                if (mimeType.Contains("jpg"))
                                {
                                    extension = ".jpeg";
                                }
                                else if (mimeType.Contains("bmp"))
                                {
                                    extension = ".bmp";
                                }
                                else if (mimeType.Contains("png"))
                                {
                                    extension = ".png";
                                }
                            }

                            // prepare file name
                            string file = string.Format(Common.MapDestinationFilePath(filePath), extension);

                            // and store it to the file system
                            System.IO.File.WriteAllBytes(file, picture.PictureData);
                        }
                    }
                }
                catch (Exception exp)
                {
                    Console.WriteLine(exp.Message);
                }
            }
Ejemplo n.º 4
0
        private void SetAPIC(FrameFlagSet ffs, byte[] data)
        {
            AttachedPictureFrame frame = new AttachedPictureFrame(ffs, data);

            if (this._APIC == null || this._APIC.Length == 0)
            {
                this._APIC = new AttachedPictureFrame[] { frame };
            }
            else
            {
                this._APIC = Generic.Add(this._APIC, frame);
            }
        }
Ejemplo n.º 5
0
            public void Process(IStatus status)
            {
                this.status = status;
                status.Report("Updataing tags...");

                ID3Info info = new ID3Info(this.source, true);

                info.ID3v1Info.HaveTag     = true;
                info.ID3v1Info.Title       = Helper.String.Clip(this.title, 30);
                info.ID3v1Info.Artist      = Helper.String.Clip(this.artist, 30);
                info.ID3v1Info.Album       = Helper.String.Clip(this.album, 30);
                info.ID3v1Info.Genre       = 255;
                info.ID3v1Info.Year        = DateTime.Now.Year.ToString();
                info.ID3v1Info.Comment     = string.Empty;
                info.ID3v1Info.TrackNumber = this.track;

                info.ID3v2Info.ClearAll();
                info.ID3v2Info.HaveTag = true;
                info.ID3v2Info.SetMinorVersion(3);
                info.ID3v2Info.SetTextFrame("TIT2", this.title);
                info.ID3v2Info.SetTextFrame("TPE1", this.artist);
                info.ID3v2Info.SetTextFrame("TALB", this.album);
                info.ID3v2Info.SetTextFrame("TCON", this.genre);
                info.ID3v2Info.SetTextFrame("TRCK", this.track.ToString());

                using (MemoryStream stream = Helper.Imaging.ImageToMemoryStream(this.artwork, System.Drawing.Imaging.ImageFormat.Jpeg))
                {
                    AttachedPictureFrame ATP = new AttachedPictureFrame(new FrameFlags(), "", TextEncodings.Ascii, "image/jpg", AttachedPictureFrame.PictureTypes.Cover_Front, stream);
                    info.ID3v2Info.AttachedPictureFrames.Add(ATP);

                    try
                    {
                        info.Save();
                    }
                    catch (Exception ex)
                    {
                        status.Report(String.Format("Unable to save tags. (\"{0}\")", ex.Message));
                    }
                }

                //info.Save();
            }
Ejemplo n.º 6
0
        private bool ViewPicture(AttachedPictureFrame AP)
        {
            try
            {
                pictureArtwork.Image = Image.FromStream(AP.Data);
                if (pictureArtwork.Image.Height < pictureArtwork.Height && pictureArtwork.Image.Width < pictureArtwork.Width)
                {
                    pictureArtwork.SizeMode = PictureBoxSizeMode.CenterImage;
                }
                else
                {
                    pictureArtwork.SizeMode = PictureBoxSizeMode.Zoom;
                }

                return(true);
            }
            catch (Exception ex)
            {
                return(false);
            }
        }
Ejemplo n.º 7
0
        public static void WriteMP3Tags(string filename, CD cd, int track)
        {
            ID3Info id3Info = new ID3Info(filename, true);

            int id3Version = Settings.Current.UseID3Version;

            int year = cd.Tracks[track].YearRecorded != 0 ? cd.Tracks[track].YearRecorded : cd.YearRecorded;

            if (id3Version == 0 || id3Version == 2)
            {
                // HACK JUS 08.04.2007: Damit ID3v2 Tags auch geschrieben werden, wenn kein ID3v2 Header vorhanden ist!
                // Ab und zu mal schauen, ob es vielleicht eine neue Version der Lib gibt
                // http://www.codeproject.com/cs/library/Do_Anything_With_ID3.asp
                id3Info.ID3v1Info.HaveTag = true;

                id3Info.ID3v1Info.Artist      = cd.Sampler ? cd.Tracks[track].Artist : cd.Artist;
                id3Info.ID3v1Info.Title       = cd.Tracks[track].Title;
                id3Info.ID3v1Info.Comment     = cd.Comment;
                id3Info.ID3v1Info.TrackNumber = (byte)(track + 1);
                id3Info.ID3v1Info.Album       = cd.Title;

                id3Info.ID3v1Info.Year = year != 0 ? year.ToString() : "";
            }

            if (id3Version == 1 || id3Version == 2)
            {
                // HACK JUS 08.04.2007: Damit ID3v2 Tags auch geschrieben werden, wenn kein ID3v2 Header vorhanden ist!
                // Ab und zu mal schauen, ob es vielleicht eine neue Version der Lib gibt
                // http://www.codeproject.com/cs/library/Do_Anything_With_ID3.asp
                id3Info.ID3v2Info.HaveTag = true;

                id3Info.ID3v2Info.SetMinorVersion(3);
                id3Info.ID3v2Info.SetTextFrame("TPE1", cd.Sampler ? cd.Tracks[track].Artist : cd.Artist);
                id3Info.ID3v2Info.SetTextFrame("TIT2", cd.Tracks[track].Title);
                id3Info.ID3v2Info.SetTextWithLanguageFrame("COMM", cd.Comment);
                id3Info.ID3v2Info.SetTextFrame("TRCK", (track + 1).ToString());
                id3Info.ID3v2Info.SetTextFrame("TALB", cd.Title);
                id3Info.ID3v2Info.SetTextFrame("TYER", year != 0 ? year.ToString() : "");

                id3Info.ID3v2Info.SetTextFrame("TCON", cd.Category);
                id3Info.ID3v2Info.SetTextFrame("TCOM", cd.Composer);
                id3Info.ID3v2Info.SetTextFrame("TLAN", cd.Language);

                // Das mit dem Rating geht irgendwie anders. Erst mal raus
                //                id3Info.ID3v2Info.PopularimeterFrames.Add(.SetTextFrame("POPM", cd.Rating > 0 ? cd.Rating.ToString() : "");

                id3Info.ID3v2Info.SetTextFrame("TBPM", cd.Tracks[track].Bpm > 0 ? cd.Tracks[track].Bpm.ToString() : "");

                id3Info.ID3v2Info.SetTextFrame("TLEN", cd.Tracks[track].Length > 0 ? cd.Tracks[track].Length.ToString() : "");
                try
                {
                    if (!string.IsNullOrEmpty(cd.CDCoverFrontFilename))
                    {
                        byte[] filefrontcover = File.ReadAllBytes(cd.CDCoverFrontFilename);
                        string mimetype;
                        mimetype = GetMIMEType(Path.GetExtension(cd.CDCoverFrontFilename));
                        MemoryStream memstream = new MemoryStream(filefrontcover);

                        AttachedPictureFrame item = new AttachedPictureFrame((FrameFlags)0, "", 0, mimetype, AttachedPictureFrame.PictureTypes.Cover_Front, memstream);
                        id3Info.ID3v2Info.AttachedPictureFrames.Add(item);
                    }
                }
                catch
                {
                    // Pech gehabt - kein Cover
                }

                try
                {
                    if (!string.IsNullOrEmpty(cd.Tracks[track].Lyrics))
                    {
                        ID3.ID3v2Frames.TextFrames.TextWithLanguageFrame textFrame = new ID3.ID3v2Frames.TextFrames.TextWithLanguageFrame("USLT", 0, cd.Tracks[track].Lyrics, "", TextEncodings.UTF_16, "und");
                        id3Info.ID3v2Info.TextWithLanguageFrames.Add(textFrame);
                    }
                }
                catch
                {
                    // Sicherheitshalber mal abgefragt
                }
            }

            try
            {
                switch (id3Version)
                {
                case 0:
                    id3Info.ID3v1Info.Save();
                    break;

                case 1:
                    id3Info.ID3v2Info.Save();
                    break;

                case 2:
                    id3Info.ID3v1Info.Save();
                    id3Info.ID3v2Info.Save();
                    break;
                }
            }
            catch (Exception e)
            {
                System.Windows.Forms.MessageBox.Show(e.ToString(), System.Windows.Forms.Application.ProductName, System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Information);
            }
        }
Ejemplo n.º 8
0
        public async Task WriteMetadata(VideoInfo videoInfo, MetaDataInfo info, ConversionTarget target)
        {
            string filePath = PathHelper.GenerateFilePath(videoInfo.FileName);

            if (!File.Exists(filePath))
            {
                return; // just no-op
            }
            var tFile = TagLib.File.Create(filePath);

            tFile.Tag.Title = string.IsNullOrWhiteSpace(info?.Title)
                ? (videoInfo.VideoTitle ?? PathHelper.GetFilenameWithoutExtension(videoInfo.FileName))
                : info.Title;

            if (target == ConversionTarget.Mp3 && !string.IsNullOrWhiteSpace(info?.Artists))
            {
                tFile.Tag.Performers = new string[] { info.Artists };
            }

            // Check if we even have to fetch and download album art :)
            if (tFile.Tag.Pictures?.Length > 0)
            {
                // Only fetch and set thumbnail once :)
                tFile.Save();
                return;
            }

            // Fetch Youtube thumbnail
            var    ytId      = PathHelper.GetFilenameWithoutExtension(videoInfo.FileName);
            string imageName = $"{ytId}.jpg";
            string imagePath = Path.Combine(PathHelper.OutputPath, imageName);

            try
            {
                await _httpService.DownloadAndSaveFile(new Uri($"https://i.ytimg.com/vi/{ytId}/maxresdefault.jpg"), imagePath);
            }
            catch (Exception)
            {
                // If we fail to download the image just return without it it's fine...
                tFile.Save();
                return;
            }

            // Add image as album cover :)
            var imageBytes = File.ReadAllBytes(imagePath);

            TagLib.Id3v2.AttachedPictureFrame cover = new AttachedPictureFrame()
            {
                Type         = TagLib.PictureType.FrontCover,
                Description  = "Cover",
                MimeType     = System.Net.Mime.MediaTypeNames.Image.Jpeg,
                Data         = imageBytes,
                TextEncoding = TagLib.StringType.UTF16
            };

            tFile.Tag.Pictures = new IPicture[] { cover };

            tFile.Save();

            // Remove file if it exists.
            if (File.Exists(imagePath))
            {
                File.Delete(imagePath);
            }
        }
Ejemplo n.º 9
0
        private bool WriteMp3Metadata()
        {
            using (TagLib.File file = TagLib.File.Create(_filepath, "taglib/mp3", ReadStyle.Average))
            {
                var tags = (Tag)file.GetTag(TagTypes.Id3v2);

                if (_coverBytes.Length > 0)
                {
                    var byteVector   = new ByteVector(_coverBytes);
                    var coverPicture = new Picture
                    {
                        Description = "Cover",
                        Data        = byteVector,
                        MimeType    = MediaTypeNames.Image.Jpeg,
                        Type        = PictureType.FrontCover
                    };
                    var attachedPictureFrame = new AttachedPictureFrame(coverPicture);

                    tags.Pictures = new IPicture[] { attachedPictureFrame };
                }

                tags.AddFrame(MetadataHelpers.BuildTextInformationFrame("TMED", "Digital Media"));

                if (_trackInfo?.TrackTags != null)
                {
                    tags.Title        = _trackInfo.TrackTags.Title;
                    tags.Performers   = _trackInfo.TrackTags.Artists.Select(x => x.Name).ToArray();
                    tags.AlbumArtists = _albumInfo.AlbumTags.Artists.Select(x => x.Name).ToArray(); // i don't like just using ART_NAME as the only album artist
                    tags.Composers    = _trackInfo.TrackTags.Contributors.Composers;

                    if (_trackInfo.TrackTags.TrackNumber != null)
                    {
                        tags.Track = uint.Parse(_trackInfo.TrackTags.TrackNumber);
                    }

                    if (_trackInfo.TrackTags.DiscNumber != null)
                    {
                        tags.Disc = uint.Parse(_trackInfo.TrackTags.DiscNumber);
                    }

                    if (_trackInfo.TrackTags.Bpm != null)
                    {
                        string bpm = _trackInfo.TrackTags.Bpm;

                        if (double.TryParse(bpm, out double bpmParsed))
                        {
                            bpmParsed = Math.Round(bpmParsed);
                            bpm       = bpmParsed.ToString(CultureInfo.InvariantCulture);
                        }

                        tags.BeatsPerMinute = uint.Parse(bpm);
                    }

                    tags.AddFrame(MetadataHelpers.BuildTextInformationFrame("TSRC", _trackInfo.TrackTags.Isrc));
                    tags.AddFrame(MetadataHelpers.BuildTextInformationFrame("TPUB", _trackInfo.TrackTags.Contributors.Publishers));
                    tags.AddFrame(MetadataHelpers.BuildTextInformationFrame("TLEN", _trackInfo.TrackTags.Length));
                    tags.AddFrame(MetadataHelpers.BuildUserTextInformationFrame("EXPLICIT", _trackInfo.TrackTags.ExplicitLyrics));
                    tags.AddFrame(MetadataHelpers.BuildUserTextInformationFrame("REPLAYGAIN_TRACK_GAIN", _trackInfo.TrackTags.Gain));
                    tags.AddFrame(MetadataHelpers.BuildUserTextInformationFrame("WRITERS", _trackInfo.TrackTags.Contributors.Writers));
                    tags.AddFrame(MetadataHelpers.BuildUserTextInformationFrame("AUTHORS", _trackInfo.TrackTags.Contributors.Authors));
                    tags.AddFrame(MetadataHelpers.BuildUserTextInformationFrame("TIPL", "PRODUCERS", _trackInfo.TrackTags.Contributors.Publishers));
                    tags.AddFrame(MetadataHelpers.BuildUserTextInformationFrame("TIPL", "ENGINEERS", _trackInfo.TrackTags.Contributors.Engineers));
                    tags.AddFrame(MetadataHelpers.BuildUserTextInformationFrame("TIPL", "MIXERS", _trackInfo.TrackTags.Contributors.Mixers));
                }

                if (_albumInfo?.AlbumTags != null)
                {
                    tags.Album  = _albumInfo.AlbumTags.Title;
                    tags.Genres = _albumInfo.AlbumTags.Genres.GenreData.Select(x => x.Name).ToArray();

                    if (_albumInfo.AlbumTags.NumberOfTracks != null)
                    {
                        tags.TrackCount = uint.Parse(_albumInfo.AlbumTags.NumberOfTracks);
                    }

                    if (_albumInfo.AlbumTags.NumberOfDiscs != null)
                    {
                        tags.DiscCount = uint.Parse(_albumInfo.AlbumTags.NumberOfDiscs);
                    }

                    if (_albumInfo.AlbumTags.Type == "Compilation" || _albumInfo.AlbumTags.Type == "Playlist")
                    {
                        tags.IsCompilation = true;
                    }

                    tags.Copyright = _albumInfo.AlbumTags.Copyright;

                    string year = _albumInfo.AlbumTags.ReleaseDate;

                    if (!string.IsNullOrWhiteSpace(year))
                    {
                        string[] yearSplit = year.Split("-");

                        if (yearSplit[0].Length == 4 && uint.TryParse(yearSplit[0], out uint yearParsed))
                        {
                            tags.Year = yearParsed;
                        }
                    }

                    tags.AddFrame(MetadataHelpers.BuildTextInformationFrame("TPUB", _albumInfo.AlbumTags.Label));
                    tags.AddFrame(MetadataHelpers.BuildTextInformationFrame("TDOR", _albumInfo.AlbumTags.ReleaseDate));
                    tags.AddFrame(MetadataHelpers.BuildUserTextInformationFrame("UPC", _albumInfo.AlbumTags.Upc));
                }

                if (_trackInfo?.Lyrics != null)
                {
                    tags.Lyrics = _trackInfo.Lyrics.UnSyncedLyrics;
                    WriteLyricsFile();
                }

                try
                {
                    file.Save();
                }
                catch (IOException ex)
                {
                    Console.WriteLine(ex.Message);
                    return(false);
                }
            }

            return(true);
        }
Ejemplo n.º 10
0
        /// <summary>
        /// 下载红心歌曲
        /// </summary>
        public void Download()
        {
            if (Directory.Exists(Path) == false)//如果不存在就创建文件夹
            {
                Directory.CreateDirectory(Path);
            }
            client.NewList();
            client.SwitchChannel(Channel.RedHeart);
            int times = 0;
            int num   = 0;

            while (dic.Count <= Total)
            {
                foreach (Song song in client.Playlist)
                {
                    if (!dic.Keys.Contains(song.SongID))
                    {
                        dic.Add(song.SongID, song);
                        num++;
                        currentSong = song;
                        string fileName = Path + song.Title + ".mp3";
                        try
                        {
                            image = Image.FromStream(WebRequest.Create(song.PictureURL).GetResponse().GetResponseStream());
                        }
                        catch (Exception)
                        {
                            image = Properties.Resources.cover;
                        }
                        NewSong.Invoke(num, image, song.Title, song.Artist);
                        if (File.Exists(fileName))
                        {
                            Exist++;
                        }
                        else
                        {
                            if (Downfile(song.MediaURL, fileName))
                            {
                                Success++;
                                ID3Info info = new ID3Info(fileName, true);
                                info.Load();
                                info.ID3v2Info.SetMinorVersion(3);
                                AttachedPictureFrame pic = null;
                                try
                                {
                                    if (!string.IsNullOrEmpty(CoverPath))//保存封面
                                    {
                                        image.Save(CoverPath + song.Title + ".jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
                                    }

                                    ms = new System.IO.MemoryStream();
                                    image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                                    // 创建新封面
                                    pic = new AttachedPictureFrame(
                                        FrameFlags.Compression, "cover.jpg", TextEncodings.UTF_16, "",
                                        AttachedPictureFrame.PictureTypes.Cover_Front, ms);
                                    info.ID3v2Info.AttachedPictureFrames.Add(pic);
                                    // 添加新封面到MP3中
                                }
                                catch
                                {
                                }

                                if (!string.IsNullOrEmpty(lyricPath))//下载歌词
                                {
                                    downloadLrc.SaveLyric(song.Artist, song.Title, lyricPath + song.Title + ".lrc");
                                }

                                // 设置其它属性(ID3V1)
                                info.ID3v1Info.Title  = song.Title;
                                info.ID3v1Info.Artist = song.Artist;
                                info.ID3v1Info.Album  = song.AlbumTitle;

                                //jasine fixed 2015.9.23
                                info.ID3v1Info.Year = song.PublicationTime;
                                //info.ID3v1Info.Year = "";

                                info.ID3v1Info.Comment = "*****@*****.**"; //注释---------添加不上去
                                info.ID3v1Info.Genre   = 12;                     //类型代码Other:12 对应于ID3V2中自定义类型RedHeart

                                // 设置其它属性(ID3V2)
                                info.ID3v2Info.SetTextFrame("TIT2", song.Title);
                                info.ID3v2Info.SetTextFrame("TPE1", song.Artist);
                                info.ID3v2Info.SetTextFrame("TALB", song.AlbumTitle);

                                //jasine fixed 2015.9.23
                                info.ID3v2Info.SetTextFrame("TYER", song.PublicationTime);
                                //info.ID3v2Info.SetTextFrame("TYER", "");

                                //info.ID3v2Info.SetTextFrame("COMM", "*****@*****.**");//注释---------添加不上去
                                info.ID3v2Info.SetTextFrame("TCON", "RedHeart");//类型

                                //jasine fixed 2015.9.23
                                //info.ID3v2Info.SetTextFrame("TPUB", song.Publisher);//发布者,发布单位
                                info.ID3v2Info.SetTextFrame("TPUB", "");//发布者,发布单位

                                // 保存到MP3中
                                if (ID3Version == 1)
                                {
                                    info.ID3v1Info.Save();
                                }
                                else
                                {
                                    //info.Save(3);
                                    info.ID3v2Info.PopularimeterFrames.Add(new ID3.ID3v2Frames.TextFrames.PopularimeterFrame(
                                                                               FrameFlags.TagAlterPreservation, "fm.douban.com", song.Rating, 0));//豆瓣评分
                                    info.ID3v2Info.Save(3);
                                }
                            }
                            else
                            {
                                //下载失败
                                Fail++;
                            }
                        }
                        if ((Success + Fail + Exist) >= Total)
                        {
                            Msg.Invoke(Success, Fail, Exist, "下载完成");
                            Stop();
                        }
                        else
                        {
                            Msg.Invoke(Success, Fail, Exist, "");
                        }
                    }
                }
                client.Skip();
                times++;
                if (times > 10000)
                {
                    Fail = Total - (Success + Exist);
                    Msg.Invoke(Success, Fail, Exist, "尝试次数过多,未成功下载歌曲请过几小时后再在原文件夹下载");
                    Stop();
                }
            }
            Msg.Invoke(Success, Fail, Exist, "下载完成");
        }