private TagLib.File OpenAudioFile(string path, string ext) // Opens a proper file format via TagLib# and gets a file hadler object { TagLib.File audioFile = null; switch (ext) // Opening correct file type with TagLib# { case "MP3": audioFile = new TagLib.Mpeg.AudioFile(path, TagLib.ReadStyle.Average); break; case "FLAC": audioFile = new TagLib.Flac.File(path, TagLib.ReadStyle.Average); break; case "APE": // Generally not supported yet audioFile = new TagLib.Ape.File(path, TagLib.ReadStyle.Average); break; case "AAC": // Generally not supported yet audioFile = new TagLib.Aac.File(path, TagLib.ReadStyle.Average); break; case "AIFF": // Generally not supported yet audioFile = new TagLib.Aiff.File(path, TagLib.ReadStyle.Average); break; default: audioFile = TagLib.File.Create(path); break; } return(audioFile); }
/// <summary> /// Воспроизвести трек /// </summary> /// <param name="url">Путь к треку</param> private void PlayTrack(string url) { WMPlayer.URL = url; //записать путь к треку в плеер TagLib.File song = TagLib.File.Create(WMPlayer.URL); //создать файл с тегами трека FullDurationLabel.Text = SecondsToTime((int)song.Properties.Duration.TotalSeconds); //выводим длительность трека TitleLabel.Text = song.Tag.Title; //выводим название трека ArtistLabel.Text = song.Tag.FirstPerformer; //выводим исполнителя трека timer1.Enabled = true; //включаем таймер для ползунка длительности PlayButton.Image = Properties.Resources.Пауза; //меняем изображение кнопки Play на паузу Player.Current = Player.Tracks.Find(track => track.FullName == url); //записываем текущий трек LikeButton.Image = Player.Current.IsLike ? Properties.Resources.Лайк : Properties.Resources.Дизлайк; WMPlayer.controls.play(); //включаем воспроизведение CoverBox.Image = Properties.Resources.cover; TagLib.File f = new TagLib.Mpeg.AudioFile(url); if (f.Tag.Pictures.Length > 0) { TagLib.IPicture pic = f.Tag.Pictures[0]; MemoryStream ms = new MemoryStream(pic.Data.Data); if (ms != null && ms.Length > 4096) { CoverBox.Image = Image.FromStream(ms).GetThumbnailImage(240, 240, null, IntPtr.Zero); } ms.Close(); } }
/// <summary> /// Нажатие на кнопку "Следующий трек" /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnNext_Click(object sender, RoutedEventArgs e) { if ((playlist.Items.Count != 0) && (playlist.SelectedIndex != -1)) { labelNowPlaying.Content = "Now playing:"; BassLike.Next(); slVol.Value = 100; labelLefttime.Content = TimeSpan.FromSeconds(BassLike.GetPosOfStream(BassLike.Stream)).ToString(); labelRightTime.Content = TimeSpan.FromSeconds(BassLike.GetTimeOfStream(BassLike.Stream)).ToString(); slTime.Maximum = BassLike.GetTimeOfStream(BassLike.Stream); slTime.Value = BassLike.GetPosOfStream(BassLike.Stream); try { if (Vars.Files.Count >= Vars.CurrentTrackNumber + 1) { ++playlist.SelectedIndex; labelCurrentPlayingName.Content = Vars.GetFileName((Vars.Files[Vars.CurrentTrackNumber])); } else if (Vars.CurrentTrackNumber == Vars.Files.Count) { labelCurrentPlayingName.Content = Vars.GetFileName(Vars.Files[playlist.SelectedIndex]); } if (BassLike.isStopped) { labelLefttime.Content = null; labelRightTime.Content = null; labelCurrentPlayingName.Content = null; } } catch { labelCurrentPlayingName.Content = null; } //***************************************************************************************// string current = Vars.Files[playlist.SelectedIndex]; try { TagLib.File f = new TagLib.Mpeg.AudioFile(current); TagLib.IPicture pic = f.Tag.Pictures[0]; var mStream = new MemoryStream(pic.Data.Data); mStream.Seek(0, SeekOrigin.Begin); BitmapImage bm = new BitmapImage(); bm.BeginInit(); bm.StreamSource = mStream; bm.EndInit(); System.Windows.Controls.Image cover = new System.Windows.Controls.Image(); cover.Source = bm; image.Source = bm; } catch { var uri = new Uri("pack://application:,,,/Resources/nocover.png"); var img = new BitmapImage(uri); image.Source = img; } //***************************************************************************************// } }
public static Image GetMetaImage(string MusicPath) { TagLib.File f = new TagLib.Mpeg.AudioFile(MusicPath); var pic = f.Tag.Pictures[0]; using (var ms = new MemoryStream(pic.Data.Data)) { var image = Image.FromStream(ms); return(image); } }
private void writeTagInfo(string title, string path, string genre, string artist) { try { bool changed = false; TagLib.Mpeg.AudioFile file = new TagLib.Mpeg.AudioFile(path); if (String.IsNullOrWhiteSpace(file.Tag.Title) || file.Tag.Title.ToLower() != title.ToLower()) { file.Tag.Title = Capitalise(title); changed = true; } ; if (file.Tag.Genres.Length == 0 || file.Tag.Genres[0].ToLower() != genre.ToLower()) { file.Tag.Genres = new string[1] { Capitalise(genre) }; changed = true; } ; if (file.Tag.Performers.Length == 0 || file.Tag.Performers[0] != artist.ToLower()) { file.Tag.Performers = new string[1] { Capitalise(artist) }; changed = true; } ; if (file.Tag.Lyrics == null) { file.Tag.Lyrics = Tracklist; changed = true; } ; if (file.Tag.Album == null || file.Tag.Album.ToLower() != album.ToLower()) { file.Tag.Album = Capitalise(album); changed = true; } if (changed) { Console.WriteLine("CHG"); file.Save(); } } catch (Exception ex) { logger.addEvent(new cEvent(Severity.Error, "An error occured while writing tags for the current file:\r\n" + "Title: " + title + "\r\n" + "Path: " + path + "\r\nGenre: " + genre + "\r\n" + artist, ex)); } }
public MP3(string songpath) { if (!songpath.ToLower().Contains(".mp3")) { throw new ArgumentException("File is not an mp3"); } if (String.IsNullOrEmpty(songpath)) { throw new ArgumentException("No songpath given"); } if (!File.Exists(songpath)) { throw new ArgumentException("File not found"); } path = songpath; file = new TagLib.Mpeg.AudioFile(songpath); }
public Audio(string filePath) : base(filePath) { if (this.Extension.ToLower() == ".mp3") { TagLib.Mpeg.AudioFile audioFile = new TagLib.Mpeg.AudioFile(filePath); _artist = audioFile.Tag.FirstAlbumArtist; _album = audioFile.Tag.Album; _genre = audioFile.Tag.FirstGenre; _lengthInSeconds = (int)Math.Round(audioFile.Properties.Duration.TotalSeconds); } else if (this.Extension.ToLower() == ".wav") { TagLib.Riff.File audioFile = new TagLib.Riff.File(filePath); _artist = audioFile.Tag.FirstAlbumArtist; _album = audioFile.Tag.Album; _genre = audioFile.Tag.FirstGenre; _lengthInSeconds = (int)Math.Round(audioFile.Properties.Duration.TotalSeconds); } else if (this.Extension.ToLower() == ".aiff") { TagLib.Aiff.File audioFile = new TagLib.Aiff.File(filePath); _artist = audioFile.Tag.FirstAlbumArtist; _album = audioFile.Tag.Album; _genre = audioFile.Tag.FirstGenre; _lengthInSeconds = (int)Math.Round(audioFile.Properties.Duration.TotalSeconds); } else if (this.Extension.ToLower() == ".flac") { TagLib.Flac.File audioFile = new TagLib.Flac.File(filePath); _artist = audioFile.Tag.FirstAlbumArtist; _album = audioFile.Tag.Album; _genre = audioFile.Tag.FirstGenre; _lengthInSeconds = (int)Math.Round(audioFile.Properties.Duration.TotalSeconds); } else if (this.Extension.ToLower() == ".aa" || this.Extension.ToLower() == ".aax") { TagLib.Audible.File audioFile = new TagLib.Audible.File(filePath); _artist = audioFile.Tag.FirstAlbumArtist; _album = audioFile.Tag.Album; _genre = audioFile.Tag.FirstGenre; _lengthInSeconds = (int)Math.Round(audioFile.Properties.Duration.TotalSeconds); } }
private void ProcessFile(string filePath) { try { AudioType?audioType = null; // Use a nullable value so that we don't have to assign a enum value TagLib.File file = null; switch (Path.GetExtension(filePath)) { case ".mp3": file = new TagLib.Mpeg.AudioFile(filePath); audioType = AudioType.Mp3; break; case ".wav": file = new TagLib.WavPack.File(filePath); audioType = AudioType.Wav; break; } if (file != null) { if (file.Tag != null) { this.AddSong(file, audioType.Value); } file.Dispose(); } } catch (CorruptFileException) { this.corruptFiles.Add(filePath); } catch (IOException) { this.corruptFiles.Add(filePath); } }
public void ScanDirectory(string path) { DirectoryInfo di = new DirectoryInfo(path); foreach (FileInfo fi in di.GetFiles()) { try { if (!fi.FullName.EndsWith(".mp3")) { continue; } TagLib.Mpeg.AudioFile audioFile = new TagLib.Mpeg.AudioFile(fi.FullName); Track track = new Track() { Artist = "", Name = audioFile.Tag.Title, Album = audioFile.Tag.Album, Url = "file://" + fi.FullName }; if (audioFile.Tag.Artists.Length > 0) { track.Artist = audioFile.Tag.Artists[0]; } DbContext.Tracks.Add(track); bw.ReportProgress(2, track); } catch (Exception e) { } } foreach (DirectoryInfo dir in di.GetDirectories()) { ScanDirectory(dir.FullName); } }
/// <summary> /// Нажатие на кнопку "Плей" /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnPlay_Click(object sender, MouseButtonEventArgs e) { if ((playlist.Items.Count != 0) && (playlist.SelectedIndex != -1)) { dtimer.Start(); labelNowPlaying.Content = "Now playing:"; string current = Vars.Files[playlist.SelectedIndex]; Vars.CurrentTrackNumber = playlist.SelectedIndex; BassLike.Play(current, BassLike.Volume); labelLefttime.Content = TimeSpan.FromSeconds(BassLike.GetPosOfStream(BassLike.Stream)).ToString(); labelRightTime.Content = TimeSpan.FromSeconds(BassLike.GetTimeOfStream(BassLike.Stream)).ToString(); slTime.Maximum = BassLike.GetTimeOfStream(BassLike.Stream); slTime.Value = BassLike.GetPosOfStream(BassLike.Stream); labelCurrentPlayingName.Content = Vars.GetFileName(current); //************************************************************************// try { TagLib.File f = new TagLib.Mpeg.AudioFile(current); TagLib.IPicture pic = f.Tag.Pictures[0]; var mStream = new MemoryStream(pic.Data.Data); mStream.Seek(0, SeekOrigin.Begin); BitmapImage bm = new BitmapImage(); bm.BeginInit(); bm.StreamSource = mStream; bm.EndInit(); System.Windows.Controls.Image cover = new System.Windows.Controls.Image(); cover.Source = bm; image.Source = bm; } catch { var uri = new Uri("pack://application:,,,/Resources/nocover.png"); var img = new BitmapImage(uri); image.Source = img;; } //***************************************************************************************// } }
public void GetImageFromMp3ForArtists(string path, string artist) { var f = new TagLib.Mpeg.AudioFile(path); if (!f.Tag.Pictures.Any()) { return; } TagLib.IPicture pic = f?.Tag?.Pictures[0]; var ms = new MemoryStream(pic.Data.Data); ms.Seek(0, SeekOrigin.Begin); BitmapImage bitmap = new BitmapImage(); bitmap.BeginInit(); bitmap.StreamSource = ms; bitmap.EndInit(); AlbumArtCollection.SharedArtistArt[artist] = bitmap; }
public ID3ArtworkInfo(TagLib.Mpeg.AudioFile af) { _af = af; ReadPictures(); }
/// <summary> /// Refreshes the metadata of the audio file. /// </summary> public void RefreshMetadata() { // Get file size #if WINDOWSSTORE fileSize = 0; #else var fileInfo = new FileInfo(filePath); fileSize = fileInfo.Length; #endif // Check what is the type of the audio file if (fileType == AudioFileFormat.MP3) { // Declare variables TagLib.Mpeg.AudioFile file = null; try { // Create a more specific type of class for MP3 files file = new TagLib.Mpeg.AudioFile(filePath); // Get the position of the first and last block firstBlockPosition = file.InvariantStartPosition; lastBlockPosition = file.InvariantEndPosition; // Copy tags FillProperties(file.Tag); // Loop through codecs (usually just one) foreach (TagLib.ICodec codec in file.Properties.Codecs) { // Convert codec into a header TagLib.Mpeg.AudioHeader header = (TagLib.Mpeg.AudioHeader)codec; // Copy properties audioChannels = header.AudioChannels; frameLength = header.AudioFrameLength; audioLayer = header.AudioLayer; sampleRate = header.AudioSampleRate; bitsPerSample = 16; // always 16-bit channelMode = header.ChannelMode; bitrate = header.AudioBitrate; length = Conversion.TimeSpanToTimeString(header.Duration); } } catch (Exception ex) { // Throw exception TODO: Check if file exists when catching the exception (to make a better error description) throw new Exception("An error occured while reading the tags and properties of the file (" + filePath + ").", ex); } finally { // Dispose file (if needed) if (file != null) file.Dispose(); } try { // // Check if there's a Xing header // XingInfoHeaderData xingHeader = XingInfoHeaderReader.ReadXingInfoHeader(filePath, firstBlockPosition); // // // Check if the read was successful // if (xingHeader.Status == XingInfoHeaderStatus.Successful) // { // // Set property value // //m_xingInfoHeader = xingHeader; // mp3EncoderDelay = xingHeader.EncoderDelay; // mp3EncoderPadding = xingHeader.EncoderPadding; // mp3EncoderVersion = xingHeader.EncoderVersion; // mp3HeaderType = xingHeader.HeaderType; // } } catch (Exception ex) { throw ex; } } else if (fileType == AudioFileFormat.FLAC) { // Declare variables TagLib.Flac.File file = null; try { // Read VorbisComment in FLAC file file = new TagLib.Flac.File(filePath); // Get the position of the first and last block firstBlockPosition = file.InvariantStartPosition; lastBlockPosition = file.InvariantEndPosition; // Copy tags FillProperties(file.Tag); // Loop through codecs (usually just one) foreach (TagLib.ICodec codec in file.Properties.Codecs) { // Convert codec into a header TagLib.Flac.StreamHeader header = (TagLib.Flac.StreamHeader)codec; // Copy properties bitrate = header.AudioBitrate; audioChannels = header.AudioChannels; sampleRate = header.AudioSampleRate; bitsPerSample = header.BitsPerSample; length = Conversion.TimeSpanToTimeString(header.Duration); } } catch (Exception ex) { // Throw exception throw new Exception("An error occured while reading the tags and properties of the file (" + filePath + ").", ex); } finally { // Dispose file (if needed) if (file != null) file.Dispose(); } } else if (fileType == AudioFileFormat.OGG) { // Declare variables TagLib.Ogg.File file = null; try { // Read VorbisComment in OGG file file = new TagLib.Ogg.File(filePath); // Get the position of the first and last block firstBlockPosition = file.InvariantStartPosition; lastBlockPosition = file.InvariantEndPosition; // Copy tags FillProperties(file.Tag); // Loop through codecs (usually just one) foreach (TagLib.ICodec codec in file.Properties.Codecs) { // Check what kind of codec is used if (codec is TagLib.Ogg.Codecs.Theora) { // Do nothing, this is useless for audio. } else if (codec is TagLib.Ogg.Codecs.Vorbis) { // Convert codec into a header TagLib.Ogg.Codecs.Vorbis header = (TagLib.Ogg.Codecs.Vorbis)codec; // Copy properties bitrate = header.AudioBitrate; audioChannels = header.AudioChannels; sampleRate = header.AudioSampleRate; bitsPerSample = 16; length = Conversion.TimeSpanToTimeString(header.Duration); } } } catch (Exception ex) { // Throw exception throw new Exception("An error occured while reading the tags and properties of the file (" + filePath + ").", ex); } finally { // Dispose file (if needed) if (file != null) file.Dispose(); } } else if (fileType == AudioFileFormat.APE) { // Monkey's Audio (APE) supports APEv2 tags. // http://en.wikipedia.org/wiki/Monkey's_Audio // Declare variables TagLib.Ape.File file = null; try { // Read APE metadata apeTag = APEMetadata.Read(filePath); // Get APEv1/v2 tags from APE file file = new TagLib.Ape.File(filePath); // Get the position of the first and last block firstBlockPosition = file.InvariantStartPosition; lastBlockPosition = file.InvariantEndPosition; // Copy tags FillProperties(file.Tag); // Loop through codecs (usually just one) foreach (TagLib.ICodec codec in file.Properties.Codecs) { // Check what kind of codec is used if (codec is TagLib.Ape.StreamHeader) { // Convert codec into a header TagLib.Ape.StreamHeader header = (TagLib.Ape.StreamHeader)codec; // Copy properties bitrate = header.AudioBitrate; audioChannels = header.AudioChannels; sampleRate = header.AudioSampleRate; bitsPerSample = 16; length = Conversion.TimeSpanToTimeString(header.Duration); } } } catch (Exception ex) { // Throw exception throw new Exception("An error occured while reading the tags and properties of the file (" + filePath + ").", ex); } finally { // Dispose file (if needed) if (file != null) file.Dispose(); } } else if (fileType == AudioFileFormat.MPC) { // MusePack (MPC) supports APEv2 tags. // http://en.wikipedia.org/wiki/Musepack try { // Try to read SV8 header sv8Tag = SV8Metadata.Read(filePath); // Set audio properties audioChannels = sv8Tag.AudioChannels; sampleRate = sv8Tag.SampleRate; bitsPerSample = 16; length = sv8Tag.Length; bitrate = sv8Tag.Bitrate; } catch (SV8TagNotFoundException exSV8) { try { // Try to read the SV7 header sv7Tag = SV7Metadata.Read(filePath); // Set audio properties audioChannels = sv7Tag.AudioChannels; sampleRate = sv7Tag.SampleRate; bitsPerSample = 16; length = sv7Tag.Length; bitrate = sv7Tag.Bitrate; } catch (SV7TagNotFoundException exSV7) { // No headers have been found! SV8TagNotFoundException finalEx = new SV8TagNotFoundException(exSV8.Message, exSV7); throw new Exception("Error: The file is not in SV7/MPC or SV8/MPC format!", finalEx); } } try { // Read APE tag apeTag = APEMetadata.Read(filePath); // Copy tags FillProperties(apeTag); } catch (Exception ex) { // Check exception if (ex is APETagNotFoundException) { // Skip file } else { throw; } } } else if (fileType == AudioFileFormat.OFR) { // TagLib does not support OFR files... // OptimFROG (OFR) supports APEv2 tags. // http://en.wikipedia.org/wiki/OptimFROG } else if (fileType == AudioFileFormat.WV) { // WavPack supports APEv2 and ID3v1 tags. // http://www.wavpack.com/wavpack_doc.html // Declare variables TagLib.WavPack.File file = null; try { // Read WavPack tags file = new TagLib.WavPack.File(filePath); // Get the position of the first and last block firstBlockPosition = file.InvariantStartPosition; lastBlockPosition = file.InvariantEndPosition; // Copy tags FillProperties(file.Tag); // Loop through codecs (usually just one) foreach (TagLib.ICodec codec in file.Properties.Codecs) { // Check what kind of codec is used if (codec is TagLib.WavPack.StreamHeader) { // Convert codec into a header TagLib.WavPack.StreamHeader header = (TagLib.WavPack.StreamHeader)codec; // Copy properties bitrate = header.AudioBitrate; audioChannels = header.AudioChannels; sampleRate = header.AudioSampleRate; bitsPerSample = 16; length = Conversion.TimeSpanToTimeString(header.Duration); } } } catch (Exception ex) { // Throw exception throw new Exception("An error occured while reading the tags and properties of the file (" + filePath + ").", ex); } finally { // Dispose file (if needed) if (file != null) file.Dispose(); } } else if (fileType == AudioFileFormat.TTA) { // The True Audio (TTA) format supports ID3v1, ID3v2 and APEv2 tags. // http://en.wikipedia.org/wiki/TTA_(codec) audioChannels = 2; sampleRate = 44100; bitsPerSample = 16; // TagLib doesn't work. } else if (fileType == AudioFileFormat.WAV) { // Declare variables TagLib.Riff.File file = null; try { // Get WAV file file = new TagLib.Riff.File(filePath); // Get the position of the first and last block firstBlockPosition = file.InvariantStartPosition; lastBlockPosition = file.InvariantEndPosition; // Copy tags FillProperties(file.Tag); // Loop through codecs (usually just one) foreach (TagLib.ICodec codec in file.Properties.Codecs) { // Check what kind of codec is used if (codec is TagLib.Riff.WaveFormatEx) { // Convert codec into a header TagLib.Riff.WaveFormatEx header = (TagLib.Riff.WaveFormatEx)codec; // Copy properties bitrate = header.AudioBitrate; audioChannels = header.AudioChannels; sampleRate = header.AudioSampleRate; bitsPerSample = 16; length = Conversion.TimeSpanToTimeString(header.Duration); } } } catch (Exception ex) { // Throw exception throw new Exception("An error occured while reading the tags and properties of the file (" + filePath + ").", ex); } finally { // Dispose file (if needed) if (file != null) file.Dispose(); } } else if (fileType == AudioFileFormat.WMA) { // Declare variables TagLib.Asf.File file = null; try { // Read ASF/WMA tags file = new TagLib.Asf.File(filePath); // Get the position of the first and last block firstBlockPosition = file.InvariantStartPosition; lastBlockPosition = file.InvariantEndPosition; // Copy tags FillProperties(file.Tag); // The right length is here, not in the codec data structure length = Conversion.TimeSpanToTimeString(file.Properties.Duration); // Loop through codecs (usually just one) foreach (TagLib.ICodec codec in file.Properties.Codecs) { // Check what kind of codec is used if (codec is TagLib.Riff.WaveFormatEx) { // Convert codec into a header TagLib.Riff.WaveFormatEx header = (TagLib.Riff.WaveFormatEx)codec; // Copy properties bitrate = header.AudioBitrate; audioChannels = header.AudioChannels; sampleRate = header.AudioSampleRate; bitsPerSample = 16; } } } catch (Exception ex) { throw ex; } finally { // Dispose file (if needed) if (file != null) file.Dispose(); } } else if (fileType == AudioFileFormat.AAC) { // Declare variables TagLib.Aac.File file = null; try { // Read AAC tags file = new TagLib.Aac.File(filePath); // Doesn't seem to work very well... } catch (Exception ex) { throw ex; } finally { // Dispose file (if needed) if (file != null) file.Dispose(); } } // If the song has no name, give filename as the name if (String.IsNullOrEmpty(Title)) { Title = Path.GetFileNameWithoutExtension(filePath); } // If the artist has no name, give it "Unknown Artist" if (String.IsNullOrEmpty(ArtistName)) { ArtistName = "Unknown Artist"; } // If the song has no album title, give it "Unknown Album" if (String.IsNullOrEmpty(AlbumTitle)) { AlbumTitle = "Unknown Album"; } }
/// <summary> /// Extracts the album art from the audio file. Returns a byte array containing the image. /// </summary> /// <param name="filePath">Audio file path</param> /// <returns>Byte array (image)</returns> public static byte[] ExtractImageByteArrayForAudioFile(string filePath) { byte[] bytes = new byte[0]; #if WINDOWSSTORE #else // Check if the file exists if (!File.Exists(filePath)) return null; #endif // Check the file extension string extension = Path.GetExtension(filePath).ToUpper(); if (extension == ".MP3") { try { // Get tags using TagLib using (TagLib.Mpeg.AudioFile file = new TagLib.Mpeg.AudioFile(filePath)) { // Can we get the image from the ID3 tags? if (file != null && file.Tag != null && file.Tag.Pictures != null && file.Tag.Pictures.Length > 0) { // Get image from ID3 tags bytes = file.Tag.Pictures[0].Data.Data; } } } catch { // Failed to recover album art. Do nothing. } } return bytes; }
/// <summary> /// Extracts album art from an audio file. /// </summary> /// <param name="filePath">Audio file path</param> /// <returns>Image (album art)</returns> public static Image ExtractImageForAudioFile(string filePath) { // Declare variables Image imageCover = null; // Check if the file exists if (!File.Exists(filePath)) { return null; } // Check the file extension string extension = Path.GetExtension(filePath).ToUpper(); if (extension == ".MP3") { try { // Get tags using TagLib using (TagLib.Mpeg.AudioFile file = new TagLib.Mpeg.AudioFile(filePath)) { // Can we get the image from the ID3 tags? if (file != null && file.Tag != null && file.Tag.Pictures != null && file.Tag.Pictures.Length > 0) { // Get image from ID3 tags ImageConverter ic = new ImageConverter(); imageCover = (Image)ic.ConvertFrom(file.Tag.Pictures[0].Data.Data); } } } catch { // Failed to recover album art. Do nothing. } } // Check if the image was found using TagLib if (imageCover == null) { // Check in the same folder for an image representing the album cover string folderPath = Path.GetDirectoryName(filePath); #if (!MACOSX && !LINUX) // Get the directory information DirectoryInfo rootDirectoryInfo = new DirectoryInfo(folderPath); // Try to find image files List<FileInfo> imageFiles = new List<FileInfo>(); imageFiles.AddRange(rootDirectoryInfo.GetFiles("folder*.JPG").ToList()); imageFiles.AddRange(rootDirectoryInfo.GetFiles("folder*.PNG").ToList()); imageFiles.AddRange(rootDirectoryInfo.GetFiles("folder*.GIF").ToList()); imageFiles.AddRange(rootDirectoryInfo.GetFiles("cover*.JPG").ToList()); imageFiles.AddRange(rootDirectoryInfo.GetFiles("cover*.PNG").ToList()); imageFiles.AddRange(rootDirectoryInfo.GetFiles("cover*.GIF").ToList()); // Check if at least one image was found if (imageFiles.Count > 0) { try { // Get image from file imageCover = Image.FromFile(imageFiles[0].FullName); } catch { Tracing.Log("Error extracting image from " + imageFiles[0].FullName); } } #endif } return imageCover; }
/// <summary> /// Saves the metadata associated with this audio file from its properties. /// </summary> public void SaveMetadata() { // Check what is the type of the audio file if (fileType == AudioFileFormat.MP3) { // Declare variables TagLib.Mpeg.AudioFile file = null; try { // Read tags file = new TagLib.Mpeg.AudioFile(filePath); // Copy tags file = (TagLib.Mpeg.AudioFile)FillTags(file); // Save metadata file.Save(); } catch (Exception ex) { // Throw exception throw new Exception("An error occured while reading/writing the tags and properties of the file (" + filePath + ").", ex); } finally { // Dispose file (if needed) if (file != null) file.Dispose(); } } else if (fileType == AudioFileFormat.FLAC) { // Declare variables TagLib.Flac.File file = null; try { // Read tags file = new TagLib.Flac.File(filePath); // Copy tags file = (TagLib.Flac.File)FillTags(file); // Save metadata file.Save(); } catch (Exception ex) { // Throw exception throw new Exception("An error occured while reading/writing the tags and properties of the file (" + filePath + ").", ex); } finally { // Dispose file (if needed) if (file != null) file.Dispose(); } } else if (fileType == AudioFileFormat.OGG) { // Declare variables TagLib.Ogg.File file = null; try { // Read tags file = new TagLib.Ogg.File(filePath); // Copy tags file = (TagLib.Ogg.File)FillTags(file); // Save metadata file.Save(); } catch (Exception ex) { // Throw exception throw new Exception("An error occured while reading/writing the tags and properties of the file (" + filePath + ").", ex); } finally { // Dispose file (if needed) if (file != null) file.Dispose(); } } else if (fileType == AudioFileFormat.APE) { // Declare variables TagLib.Ape.File file = null; try { // Read tags file = new TagLib.Ape.File(filePath); // Copy tags file = (TagLib.Ape.File)FillTags(file); // Save metadata file.Save(); } catch (Exception ex) { // Throw exception throw new Exception("An error occured while reading/writing the tags and properties of the file (" + filePath + ").", ex); } finally { // Dispose file (if needed) if (file != null) file.Dispose(); } } else if (fileType == AudioFileFormat.WV) { // Declare variables TagLib.WavPack.File file = null; try { // Read tags file = new TagLib.WavPack.File(filePath); // Copy tags file = (TagLib.WavPack.File)FillTags(file); // Save metadata file.Save(); } catch (Exception ex) { // Throw exception throw new Exception("An error occured while reading/writing the tags and properties of the file (" + filePath + ").", ex); } finally { // Dispose file (if needed) if (file != null) file.Dispose(); } } else if (fileType == AudioFileFormat.WMA) { // Declare variables TagLib.Asf.File file = null; try { // Read tags file = new TagLib.Asf.File(filePath); // Copy tags file = (TagLib.Asf.File)FillTags(file); // Save metadata file.Save(); } catch (Exception ex) { // Throw exception throw new Exception("An error occured while reading/writing the tags and properties of the file (" + filePath + ").", ex); } finally { // Dispose file (if needed) if (file != null) file.Dispose(); } } }
public ID3ArtworkInfo(TagLib.Mpeg.AudioFile af) { _af = af; ReadPictures(); }
private void AddItemIntoPlaylist() { OpenFileDialog ofd = new OpenFileDialog(); TagLib.File file; PlaylistItem tmp; if (list.SelectedItem != null) { if (ofd.ShowDialog() == true) { string extention = System.IO.Path.GetExtension(ofd.FileName); if (extention.Equals(".mp3")) { file = new TagLib.Mpeg.AudioFile(ofd.FileName); if (file.Tag.Album != null && file.Tag.Title != null && file.Tag.FirstPerformer != null && file.Properties.Duration.TotalSeconds != 0) { tmp = new PlaylistItem { ALBUM = file.Tag.Album, TITLE = file.Tag.Title, ARTIST = file.Tag.FirstPerformer, LENGHT = file.Properties.Duration.Hours.ToString() + ":" + file.Properties.Duration.Minutes.ToString() + ":" + file.Properties.Duration.Seconds, PATH = ofd.FileName }; curr_play.Items.Add(tmp); XMLAddItem(tmp); } } else if (extention.Equals(".avi") || extention.Equals(".mp4") || extention.Equals(".wmv")) { file = TagLib.File.Create(ofd.FileName); if (file.Properties.Duration.TotalSeconds != 0) { tmp = new PlaylistItem { ALBUM = "<videofile>", TITLE = System.IO.Path.GetFileName(ofd.FileName), ARTIST = "<videofile>", LENGHT = file.Properties.Duration.Hours.ToString() + ":" + file.Properties.Duration.Minutes.ToString() + ":" + file.Properties.Duration.Seconds, PATH = ofd.FileName }; curr_play.Items.Add(tmp); XMLAddItem(tmp); } } else if (extention.Equals(".png") || extention.Equals(".gif") || extention.Equals(".jpg") || extention.Equals(".jpeg")) { if (System.IO.Path.GetFileName(ofd.FileName) != null) { tmp = new PlaylistItem { ALBUM = "<image>", TITLE = System.IO.Path.GetFileName(ofd.FileName), ARTIST = "<image>", LENGHT = "<image>", PATH = ofd.FileName }; curr_play.Items.Add(tmp); XMLAddItem(tmp); } } else { MessageBox.Show("Не удалось добавить файл!"); } } } else { MessageBox.Show("Нет выбраных плейлистов!"); } }
/// <summary> /// Gets the tags of the song for every sound format. /// Uses TagLib# by default. If TagLib# fails, the method uses FMOD's tagging system. /// </summary> /// <returns>List of tags</returns> public Tags GetTags() { // Create variables Tags tags = new Tags(); // Try to get tags from TagLib try { // Get tags if (FilePath.ToUpper().Contains("MP3")) { TagLib.Mpeg.AudioFile a = new TagLib.Mpeg.AudioFile(FilePath); foreach(TagLib.ICodec codec in a.Properties.Codecs) { TagLib.Mpeg.AudioHeader header = (TagLib.Mpeg.AudioHeader)codec; //if (header == null) //{ // break; //} } tags = GetID3Tags(); //TagLib.Mpeg.VBRIHeader b = new TagLib.Mpeg.VBRIHeader(); //TagLib.Mpeg.AudioHeader c = new TagLib.Mpeg.AudioHeader(); } TagLib.File songInfo = TagLib.File.Create(FilePath); // Get album artist if available if (songInfo.Tag.AlbumArtists.Length > 0) { tags.ArtistName = songInfo.Tag.AlbumArtists[0]; } // But by default we are taking the artists else if (songInfo.Tag.Artists.Length > 0) { tags.ArtistName = songInfo.Tag.Artists[0]; } // Get other tags if (!string.IsNullOrEmpty(songInfo.Tag.Album)) { tags.AlbumTitle = songInfo.Tag.Album; } // Set other properties tags.Title = songInfo.Tag.Title; tags.TrackNumber = songInfo.Tag.Track.ToString(); tags.DiscNumber = songInfo.Tag.Disc.ToString(); tags.Year = songInfo.Tag.Year.ToString(); tags.Genre = string.Empty; return tags; } catch (Exception ex) { // Continue with FMOD instead } // Determine sound format string extension = Path.GetExtension(FilePath).ToUpper(); if(extension.Contains("FLAC") || extension.Contains("OGG")) { // Get Vorbis Comments tags = GetVorbisComments(); } else if (extension.Contains("MP3")) { // Get ID3 tags tags = GetID3Tags(); } return tags; }
public void LoadSongDatabase() { List <Song> SongListTmp = new List <Song>(); XmlDocument PlaylistXML = new XmlDocument(); string databasePath = VdjDirectory + "\\database.xml"; using (FileStream fileStream = new FileStream(databasePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { PlaylistXML.Load(fileStream); } XmlNodeList AllSongs = PlaylistXML.GetElementsByTagName("Song"); List <XmlNode> SongNodeList = new List <XmlNode>(); for (int i = 0; i < AllSongs.Count; i++) { if (AllSongs[i].InnerXml.StartsWith("<Tags Author") == true) { SongNodeList.Add(AllSongs[i]); } } for (int i10 = 0; i10 < SongNodeList.Count; i10++) { string songKey = SongNodeList[i10].Attributes[0].Value; if (songKey.Substring(songKey.Length - 4)[0].Equals('.')) { if (songKey.LastIndexOf('\\') > 0) { bool isRepeatTitle = false; bool isFeatureFlag = false; string songPath = songKey; string songInfo = songKey.Remove(0, songKey.LastIndexOf('\\') + 1); songInfo = songInfo.Remove(songInfo.Length - 4); int tmpSeparator = songInfo.IndexOf("-"); string leadAuthor = songInfo.Remove(tmpSeparator - 1); string[] leadAuthorArray = leadAuthor.Split(','); if (leadAuthorArray.Length > 1) { for (int i1 = 1; i1 < leadAuthorArray.Length; i1++) { leadAuthorArray[i1] = leadAuthorArray[i1].Remove(0, 1); } } string title = songInfo.Remove(0, tmpSeparator + 2); string featureAuthor = title; if (title.Contains("(feat")) { int tmpFeat = title.IndexOf("(feat"); featureAuthor = title.Remove(0, tmpFeat); title = title.Remove(tmpFeat - 1); isFeatureFlag = true; } for (int i2 = 0; i2 < SongListTmp.Count; i2++) { if (SongListTmp[i2].Title == title && SongListTmp[i2].LeadAuthorList[0] == leadAuthorArray[0]) { isRepeatTitle = true; } } if (isRepeatTitle == false) { Song song = new Song(title); TagLib.File songFile = new TagLib.Mpeg.AudioFile(songPath); IPicture cover = songFile.Tag.Pictures[0]; MemoryStream tmpStream = new MemoryStream(cover.Data.Data); tmpStream.Seek(0, SeekOrigin.Begin); BitmapImage songCoverImage = new BitmapImage(); songCoverImage.BeginInit(); songCoverImage.StreamSource = tmpStream; songCoverImage.DecodePixelHeight = 200; songCoverImage.DecodePixelWidth = 200; songCoverImage.EndInit(); byte[] imageByte; JpegBitmapEncoder tmpEncoder = new JpegBitmapEncoder(); tmpEncoder.Frames.Add(BitmapFrame.Create(songCoverImage)); using (MemoryStream tmpMS = new MemoryStream()) { tmpEncoder.Save(tmpMS); imageByte = tmpMS.ToArray(); } song.CoverArt = imageByte; song.Cover = Convert.ToBase64String(imageByte); song.Album = songFile.Tag.Album; for (int i3 = 0; i3 < leadAuthorArray.Length; i3++) { song.LeadAuthorList.Add(leadAuthorArray[i3]); song.LeadAuthor = song.LeadAuthor + leadAuthorArray[i3] + ", "; } song.LeadAuthor = song.LeadAuthor.Remove(song.LeadAuthor.Length - 2); if (isFeatureFlag == true) { featureAuthor = featureAuthor.Remove(0, 7); featureAuthor = featureAuthor.Remove(featureAuthor.Length - 1); song.FeatureAuthor = featureAuthor; string[] featureAuthorArray = featureAuthor.Split(','); if (featureAuthorArray.Length > 1) { for (int i4 = 1; i4 < featureAuthorArray.Length; i4++) { featureAuthorArray[i4] = featureAuthorArray[i4].Remove(0, 1); } } for (int i5 = 0; i5 < featureAuthorArray.Length; i5++) { song.FeatureAuthorList.Add(featureAuthorArray[i5]); } song.FullAuthor = song.LeadAuthor + " feat. " + song.FeatureAuthor; } else { song.FullAuthor = song.LeadAuthor; } song.Id = SongFirstId; SongFirstId++; SongListTmp.Add(song); } } } } SongList = SongListTmp; }
/// <summary> /// Описано задание значений максимальной длины трека, минимально длины трека и значения ползунка /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void dtimer_Tick(object sender, EventArgs e) { if ((playlist.Items.Count != 0) && (playlist.SelectedIndex != -1)) { slTime.Minimum = 0; //Получаем значения посекундного измения времени трека при проигывании + вследствие этого движется ползунок slTime.Maximum = BassLike.GetTimeOfStream(BassLike.Stream); slTime.Value = BassLike.GetPosOfStream(BassLike.Stream); if (BassLike.ToNextTrack() == true) { if ((playlist.Items.Count != 0) && (playlist.SelectedIndex != -1)) { BassLike.Stop(); btnNext_Click(this, new RoutedEventArgs()); btnPrev_Click(this, new RoutedEventArgs()); btnPlay_Click(this, new RoutedEventArgs()); slVol.Value = 100; labelNowPlaying.Content = "Now playing:"; BassLike.Next(); labelLefttime.Content = TimeSpan.FromSeconds(BassLike.GetPosOfStream(BassLike.Stream)).ToString(); labelRightTime.Content = TimeSpan.FromSeconds(BassLike.GetTimeOfStream(BassLike.Stream)).ToString(); slTime.Maximum = BassLike.GetTimeOfStream(BassLike.Stream); slTime.Value = BassLike.GetPosOfStream(BassLike.Stream); try { if (Vars.Files.Count >= Vars.CurrentTrackNumber + 1) { ++playlist.SelectedIndex; labelCurrentPlayingName.Content = Vars.GetFileName((Vars.Files[Vars.CurrentTrackNumber])); } if (Vars.CurrentTrackNumber == Vars.Files.Count) { labelCurrentPlayingName.Content = Vars.GetFileName(Vars.Files[playlist.SelectedIndex]); } if (Vars.CurrentTrackNumber == 0) { playlist.SelectedIndex = 0; labelCurrentPlayingName.Content = Vars.GetFileName(Vars.Files[0]); } if (BassLike.isStopped) { labelLefttime.Content = null; labelRightTime.Content = null; labelCurrentPlayingName.Content = null; } } catch { labelCurrentPlayingName.Content = null; } } //*********************************************************// string current = Vars.Files[playlist.SelectedIndex]; Vars.CurrentTrackNumber = playlist.SelectedIndex; labelCurrentPlayingName.Content = Vars.GetFileName(current); try { TagLib.File f = new TagLib.Mpeg.AudioFile(current); TagLib.IPicture pic = f.Tag.Pictures[0]; var mStream = new MemoryStream(pic.Data.Data); mStream.Seek(0, SeekOrigin.Begin); BitmapImage bm = new BitmapImage(); bm.BeginInit(); bm.StreamSource = mStream; bm.EndInit(); System.Windows.Controls.Image cover = new System.Windows.Controls.Image(); cover.Source = bm; image.Source = bm; } catch { var uri = new Uri("pack://application:,,,/Resources/nocover.png"); var img = new BitmapImage(uri); image.Source = img; } //***************************************************************************************// } if (BassLike.endPlaylist) { btnStop_Click(this, new RoutedEventArgs()); playlist.SelectedIndex = Vars.CurrentTrackNumber = 0; BassLike.endPlaylist = false; } } }
public void LoadSong(string path) { file = new TagLib.Mpeg.AudioFile(path); this.path = path; }
private void listBox1_SelectedIndexChanged(object sender, EventArgs e) { listBox2.SelectedIndex = listBox1.SelectedIndex; string dir; dir = Convert.ToString(listBox2.SelectedItem); axWindowsMediaPlayer1.URL = dir; System.Drawing.Image currentImage = null; if (dir.Contains(".mp4") || dir.Contains(".flv")) { pictureBox1.Image = null; axWindowsMediaPlayer1.Top = 5; axWindowsMediaPlayer1.Height = 422; } else if (dir.Contains(".mp3")) { axWindowsMediaPlayer1.Top = 210; axWindowsMediaPlayer1.Height = 98; // In method onclick of the listbox showing all mp3's TagLib.File f = new TagLib.Mpeg.AudioFile(dir); if (f.Tag.Pictures.Length > 0) { songTitle = f.Tag.Title; TagLib.IPicture pic = f.Tag.Pictures[0]; MemoryStream ms = new MemoryStream(pic.Data.Data); if (ms != null && ms.Length > 4096) { currentImage = System.Drawing.Image.FromStream(ms); // Load thumbnail into PictureBox pictureBox1.Image = currentImage.GetThumbnailImage(422, 298, null, System.IntPtr.Zero); } ms.Close(); } } else { pictureBox1.Image = null; axWindowsMediaPlayer1.Top = 5; axWindowsMediaPlayer1.Height = 422; } axWindowsMediaPlayer1.Ctlcontrols.play(); }