public Stream LoadAlbumImage(string filePath) { try { TagFile file = TagFile.Create(filePath); if (file.Tag.Pictures.Length == 0) { return(null); } MemoryStream result = new MemoryStream(file.Tag.Pictures[0].Data.Data); return(result); } catch (Exception) { return(null); } }
public bool SaveAlbumImage(string filePath, byte[] imgBytes) { try { var file = TagFile.Create(filePath); var picList = new List <TagPicture> { new TagPicture(imgBytes) }; file.Tag.Pictures = picList.ToArray(); file.Save(); return(true); } catch (Exception) { return(false); } }
public byte[] AlbumArt(int index) { if (index < 0 || index >= AlbumArtCount || !IOFile.Exists(FileName)) { return(null); } try { using (var mediaFile = TagLibFile.Create(FileName)) { return(mediaFile.Tag.Pictures[index].Data.Data); } } catch (IndexOutOfRangeException) { return(null); } }
public Mp3File(string path) { FilePath = path; File f = File.Create(path); Duration = String.Format("{0}:{1:00}", f.Properties.Duration.Minutes, f.Properties.Duration.Seconds); Title = f.Tag.Title; Author = f.Tag.FirstPerformer; MaxPosition = f.Properties.Duration.TotalSeconds; //retrieving album cover as byte array and convering it into bitmapimage if (f.Tag.Pictures.Length != 0) { var img = f.Tag.Pictures[0].Data.Data; AlbumCover = new BitmapImage(); AlbumCover.BeginInit(); AlbumCover.StreamSource = new MemoryStream(img); AlbumCover.EndInit(); } }
private async Task <bool> TryLoadWithTagLibSharp(FileInfo filename) { File info = null; try { await Task.Run(() => info = File.Create(filename.FullName)); } catch (Exception) { return(false); } try { using (info) { Artist = RemoveInvalidXmlChars(!string.IsNullOrWhiteSpace(info.Tag.FirstPerformer) ? info.Tag.FirstPerformer : info.Tag.FirstAlbumArtist); Title = !string.IsNullOrWhiteSpace(info.Tag.Title) ? RemoveInvalidXmlChars(info.Tag.Title) : System.IO.Path.GetFileNameWithoutExtension(filename.FullName); Album = RemoveInvalidXmlChars(info.Tag.Album); Genres = new List <Genre>(info.Tag.Genres.Select(StringToGenre)); if (info.Properties.AudioBitrate > 56000) //No idea what TagLib# is thinking, but sometimes it shows the bitrate * 1000 { kbps = (int)Math.Round(info.Properties.AudioBitrate / (double)1000, 0); } else { kbps = info.Properties.AudioBitrate; } kHz = info.Properties.AudioSampleRate / 1000; Year = info.Tag.Year; SetDuration(info.Properties.Duration); } return(true); } catch (Exception) { return(false); } }
public void Load() { List <FileInfo> fileInfos = new List <FileInfo>(); Skin.Render("Enter the way to folder with music"); string path = Console.ReadLine(); DirectoryInfo directoryInfo = new DirectoryInfo(path); foreach (var file in directoryInfo.GetFiles("*.wav")) { fileInfos.Add(file); } foreach (var file in fileInfos) { var audio = File.Create(file.FullName); Songs.Add(new Song() { Album = new Album(audio?.Tag.Album, (int)audio.Tag?.Year), Artist = new Artist(audio.Tag?.FirstPerformer), Duration = (int)audio.Properties.Duration.TotalSeconds, Genre = audio.Tag?.FirstGenre, Lyrics = audio.Tag?.Lyrics, Title = audio.Tag?.Title, Path = audio.Name }); } }
public void RenameFile(string pathToFile) { try { var tagFile = File.Create(pathToFile); var artist = tagFile.Tag.FirstAlbumArtist; var title = tagFile.Tag.Title; if (String.IsNullOrEmpty(artist) || String.IsNullOrEmpty(title)) { return; } var fileInfo = new FileInfo(pathToFile); var newNameWithoutExtension = $"{ artist } - { title }"; fileInfo.Rename(newNameWithoutExtension); } catch (Exception ex) { _logger.LogError(ex.ToString()); } }
private static bool TryGetAlbumArtFromFile(string fileName, out BitmapImage albumArt) { albumArt = new BitmapImage(); using (TagFile tags = TagFile.Create(fileName)) { if (tags.Tag.Pictures.Any()) { using (MemoryStream ms = new MemoryStream(tags.Tag.Pictures.FirstOrDefault().Data.Data)) { albumArt.BeginInit(); albumArt.StreamSource = ms; albumArt.CacheOption = BitmapCacheOption.OnLoad; albumArt.EndInit(); albumArt.Freeze(); return(true); } } } return(false); }
private void fillSongs() { //TODO: Add compatibility with other sound file types int i = 1, j = 0; Song song; var pathlist = Configs.getPaths(); while (j < pathlist.Count) { var directoryInfo = new DirectoryInfo(pathlist[j]); foreach (var file in directoryInfo.GetFiles("*.mp3")) { song = new Song(); var tagFile = File.Create(file.FullName); var duration = tagFile.Properties.Duration; song.Count = i; song.Title = tagFile.Tag.Title; song.Duration = calcTime(duration.Seconds, duration.Minutes); // TODO: Playcount? song.Genre = tagFile.Tag.FirstGenre; song.Album = tagFile.Tag.Album; song.DateAdded = tagFile.Tag.DateTagged.ToString(); //TODO: Save Header positions + size and preferred sorting GridSongs.Items.Add(song); songDictionary.Add(pathlist[j] + Path.DirectorySeparatorChar + song.Title + ".mp3"); //TODO: Fix Index by saving it in a temporary list i++; } j++; } //If I can sort Gridsongs, use this one as well: songDictionary.Sort(); } //TODO: Filter example: https://docs.microsoft.com/en-us/windows/communitytoolkit/controls/datagrid_guidance/group_sort_filter
protected async override Task LoadImage(DirectoryInfo albumCoverDirectory) { try { using (var file = File.Create(Path)) { if (file.Tag.Pictures != null && file.Tag.Pictures.Any()) { Image = ImageHelper.ByteArrayToBitmapImage(file.Tag.Pictures.First().Data.ToArray()); return; } } } catch { // ignored } Image = MusicCoverManager.GetAlbumImage(this, albumCoverDirectory); if (Image != null) { return; } if (AnyListenSettings.Instance.Config.LoadAlbumCoverFromInternet) { try { Image = await MusicCoverManager.LoadCoverFromWeb(this, albumCoverDirectory); } catch (WebException) { //Happens, doesn't matter } } }
private void MaybeInit() { if (initialized) { return; } try { using (var tl = File.Create(new TagLibFileAbstraction(Item))) { try { width = tl.Properties.PhotoWidth; height = tl.Properties.PhotoHeight; } catch (Exception ex) { Debug("Failed to transpose Properties props", ex); } try { var t = ((TagLib.Image.File)tl).ImageTag; title = t.Title; if (string.IsNullOrWhiteSpace(title)) { title = null; } description = t.Comment; if (string.IsNullOrWhiteSpace(description)) { description = null; } creator = t.Creator; if (string.IsNullOrWhiteSpace(creator)) { creator = null; } } catch (Exception ex) { Debug("Failed to transpose Tag props", ex); } } initialized = true; Server.UpdateFileCache(this); } catch (CorruptFileException ex) { Debug( "Failed to read meta data via taglib for file " + Item.FullName, ex); initialized = true; } catch (Exception ex) { Warn( "Unhandled exception reading meta data for file " + Item.FullName, ex); } }
private async Task CreateExcelAsync(DiscordClient client) { var overallPlDuration = TimeSpan.Zero; using (var package = new ExcelPackage()) { client.DebugLogger.LogMessage(LogLevel.Info, client.CurrentUser.Username, "Обновление начато", DateTime.Now); ExcelWorksheet infoWorksheet = package.Workbook.Worksheets.Add("Info"); // Filling infoworksheet. infoWorksheet.Cells[1, 1].Value = "Big Daddy's Playlist"; infoWorksheet.Cells[1, 1, 1, 10].Merge = true; infoWorksheet.Cells[1, 1, 1, 10].Style.Font.Bold = true; infoWorksheet.Cells[2, 1].Value = "Количество песен"; infoWorksheet.Cells[2, 2].Value = await this.Database.Playlist.CountAsync(); infoWorksheet.Cells[3, 1].Value = "Дата последнего обновления"; infoWorksheet.Cells[3, 2].Value = DateTime.Now.ToString("dddd, MMM dd yyyy", new CultureInfo("ru-RU")); infoWorksheet.Cells[4, 1].Value = "Длина всех плейлистов"; infoWorksheet.Cells.AutoFitColumns(1, 40); // We will pass value here after we would know length of every playlist and get the sum. client.DebugLogger.LogMessage(LogLevel.Info, client.CurrentUser.Username, "Инфо-страница заполнена", DateTime.Now); // Filling info for each playlist in DB. foreach (var playlist in this.Database.Playlist.Select(x => x.PlaylistName).Distinct()) { TimeSpan plDuration = TimeSpan.Zero; client.DebugLogger.LogMessage(LogLevel.Info, client.CurrentUser.Username, $"Начата запись в таблицу {playlist}", DateTime.Now); ExcelWorksheet playlistWorksheet = package.Workbook.Worksheets.Add(playlist); playlistWorksheet.Cells[2, 1].Value = "№"; playlistWorksheet.Cells[2, 2].Value = "Title"; playlistWorksheet.Cells[2, 3].Value = "Artist"; playlistWorksheet.Cells[2, 4].Value = "Album"; playlistWorksheet.Cells[2, 5].Value = "Date"; playlistWorksheet.Cells[2, 6].Value = "Requested by"; foreach (var cell in playlistWorksheet.Cells[2, 1, 2, 6]) { cell.Style.Border.BorderAround(ExcelBorderStyle.Thick, System.Drawing.Color.Black); cell.Style.Font.Size = 24; } string[] songs = await this.Database.Playlist.Where(x => x.PlaylistName == playlist).Select(x => x.Path).ToArrayAsync(); var songsFiles = new List <File>(); foreach (var song in songs) { songsFiles.Add(File.Create(song)); } songsFiles = songsFiles.OrderBy(x => x.Tag.FirstPerformer + x.Tag.Year.ToString() + x.Tag.Album + x.Tag.Track).ToList(); int songNum = 1, currentRow = 3; foreach (var song in songsFiles) { playlistWorksheet.Cells[currentRow, 1].Value = songNum; playlistWorksheet.Cells[currentRow, 2].Value = $"{song.Tag.Track}.{song.Tag.Title}"; playlistWorksheet.Cells[currentRow, 3].Value = song.Tag.FirstPerformer; playlistWorksheet.Cells[currentRow, 4].Value = song.Tag.Album; playlistWorksheet.Cells[currentRow, 5].Value = song.Tag.Year; if (ulong.TryParse(song.Tag.FirstComposer, out ulong addedById)) { var user = await client.GetUserAsync(addedById).ConfigureAwait(false); playlistWorksheet.Cells[currentRow, 6].Value = $"@{user.Username}"; } else { playlistWorksheet.Cells[currentRow, 6].Value = "~~~~~~~~~~~~~"; } songNum++; currentRow++; plDuration = plDuration.Add(song.Properties.Duration); } playlistWorksheet.Cells[3, 1, currentRow - 1, 6].Style.Border.BorderAround(ExcelBorderStyle.Thin, System.Drawing.Color.Black); playlistWorksheet.Cells[3, 1, currentRow, 6].Style.Font.Size = 10; playlistWorksheet.Cells.AutoFitColumns(0.5, 80.0); playlistWorksheet.Cells[1, 1].Value = $"Длительность плейлиста: {plDuration:dd\\.hh\\:mm\\:ss}"; overallPlDuration = overallPlDuration.Add(plDuration); client.DebugLogger.LogMessage(LogLevel.Info, client.CurrentUser.Username, $"Закончена запись в таблицу {playlist}", DateTime.Now); } infoWorksheet.Cells[4, 2].Value = overallPlDuration.ToString(@"dd\.hh\:mm\:ss"); client.DebugLogger.LogMessage(LogLevel.Info, client.CurrentUser.Username, "Запись закончена", DateTime.Now); package.SaveAs(new FileInfo($@"..\..\..\Playlists\{DateTime.Today:d}.xlsx")); } }
private async Task <PlayableBase> GetTrack(FileInfo fileInfo, List <string> supportedExtensions) { var extension = fileInfo.Extension.Remove(0, 1); //--- STEP 1: Check the track --- //Check the extension if (!supportedExtensions.Any(x => string.Equals(x, extension, StringComparison.OrdinalIgnoreCase))) { return(null); } AudioInformation audioInformation = null; //Check the file if ( !(await Task.Run( () => _musicDataManager.MusicManager.AudioEngine.TestAudioFile(fileInfo.FullName, out audioInformation)))) //If the audio engine can't open the track, skip { return(null); } LocalPlayable track; //--- STEP 2: Get information from the file --- //Search if track is already in the database if (SearchTrack(fileInfo.FullName, out track)) { return(track); } //Create a new track with some information we already have track = new LocalPlayable { Extension = extension.ToUpper(), TrackPath = fileInfo.FullName, Duration = audioInformation.Duration, SampleRate = Math.Round(audioInformation.SampleRate / 1000d, 1) }; string filenameArtistName = null; string tagArtistName = null; string internetArtistName = null; string albumName = null; string title = null; /* * Information priority: * 1. Tag * 2. Internet * 3. Filename */ try { //Let's have a look in the tags using (var tagLibInfo = File.Create(fileInfo.FullName)) //We look into the tags. Perhaps we'll find something interesting { track.Title = tagLibInfo.Tag.Title; if (!string.IsNullOrEmpty(tagLibInfo.Tag.MusicBrainzArtistId)) { track.Artist = await GetArtistByMusicBrainzId(tagLibInfo.Tag.MusicBrainzArtistId); //Ui, that's awesome } else { tagArtistName = tagLibInfo.Tag.FirstPerformer ?? tagLibInfo.Tag.FirstAlbumArtist; //Both is okay } if (tagLibInfo.Tag.Pictures.Any()) { if (tagLibInfo.Tag.Pictures.Count() > 1) { Debug.Print("tagLibInfo.Tag.Pictures.Length > 1"); } track.Cover = new TagImage(fileInfo.FullName); } track.Bitrate = tagLibInfo.Properties.AudioBitrate; albumName = tagLibInfo.Tag.Album; } } catch (Exception) { //Do nothing } //At the next step, the title must have a value if (track.Title == null || (tagArtistName == null && track.Artist == null)) { var match = Regex.Match(Path.GetFileNameWithoutExtension(fileInfo.FullName), @"(?<artist>([a-zA-Z].+?)) - (?<title>(.[^\(\[-]+))"); if (match.Success) { title = match.Groups["title"].Value.Trim(); if (tagArtistName == null) { filenameArtistName = match.Groups["artist"].Value; } } else { title = Path.GetFileNameWithoutExtension(fileInfo.FullName); if (tagArtistName == null) { filenameArtistName = string.Empty; } } } //Now we search the track in the internet. If we have find something, we set all information which has to be set var trackInfo = await _musicDataManager.LastfmApi.GetTrackInformation(track.Title ?? title, track.Artist?.Name ?? tagArtistName ?? filenameArtistName); if (trackInfo != null) { if (track.Title == null) { track.Title = trackInfo.Name; } if (!string.IsNullOrEmpty(trackInfo.MusicBrainzId)) { var temp = SearchTrackByMusicBrainzId(trackInfo.MusicBrainzId); if (temp != null) { return(temp); } //Check if we already have a track with this id track.MusicBrainzId = trackInfo.MusicBrainzId; } if (track.Cover == null) { track.Cover = trackInfo.CoverImage; } if (track.Artist == null) { track.Artist = await SearchArtist(tagArtistName, trackInfo.Artist, filenameArtistName, track.MusicBrainzId); if (track.Artist == null) { internetArtistName = trackInfo.Artist; } } } else if (track.Title == null) { track.Title = title; } if (track.Artist == null) { var name = tagArtistName ?? internetArtistName ?? filenameArtistName; if (!string.IsNullOrEmpty(name)) { var artist = await _musicDataManager.LastfmApi.SearchArtistOnline(name); track.Artist = artist ?? new Artist(name); } else { track.Artist = _musicDataManager.Artists.UnknownArtist; } } if (!_musicDataManager.Artists.ArtistDictionary.ContainsKey(track.Artist.Guid)) { await _musicDataManager.Artists.AddArtist(track.Artist); } if (!string.IsNullOrWhiteSpace(albumName)) { track.Album = _musicDataManager.Albums.Collection.FirstOrDefault( x => string.Equals(x.Value.Name, albumName, StringComparison.OrdinalIgnoreCase)).Value; if (track.Album == null) { var album = new Album { Name = albumName, Guid = Guid.NewGuid() }; await _musicDataManager.Albums.AddAlbum(album); track.Album = album; } if (track.Artist != _musicDataManager.Artists.UnknownArtist && !track.Album.Artists.Contains(track.Artist)) { track.Album.Artists.Add(track.Artist); await _musicDataManager.Albums.UpdateAlbumArtists(track.Album); } } await _musicDataManager.Tracks.AddTrack(track); return(track); }
private void RippingThread() { if (_main.TreeView.InvokeRequired) { ThreadSafeGridDelegate d = RippingThread; _main.TreeView.Invoke(d, new object[] { }); return; } if (_selectedCDRomDrive == "") { log.Info("No CD drive selected. Rip not started."); return; } log.Trace(">>>"); string targetDir = ""; string encoder = null; try { _musicDir = _main.RipOutputDirectory; if (_main.RipEncoderCombo.SelectedItem != null) { encoder = (string)(_main.RipEncoderCombo.SelectedItem as Item).Value; Options.MainSettings.RipEncoder = encoder; } else { encoder = Options.MainSettings.RipEncoder; } if (encoder == null) { return; } log.Debug("Rip: Using Encoder: {0}", encoder); try { if (!Directory.Exists(_musicDir) && !string.IsNullOrEmpty(_musicDir)) { Directory.CreateDirectory(_musicDir); } } catch (Exception ex) { SetStatusLabel(localisation.ToString("Conversion", "ErrorDirectory")); log.Error("Error creating Ripping directory: {0}. {1}", _musicDir, ex.Message); return; } // Build the Target Directory string artistDir = tbAlbumArtist.Text == string.Empty ? "Artist" : tbAlbumArtist.Text; string albumDir = tbAlbum.Text == string.Empty ? "Album" : tbAlbum.Text; string outFileFormat = Options.MainSettings.RipFileNameFormat; int index = outFileFormat.LastIndexOf('\\'); if (index > -1) { targetDir = outFileFormat.Substring(0, index); targetDir = targetDir.Replace("<A>", artistDir); targetDir = targetDir.Replace("<O>", artistDir); targetDir = targetDir.Replace("<B>", albumDir); targetDir = targetDir.Replace("<G>", tbGenre.Text); targetDir = targetDir.Replace("<Y>", tbYear.Text); outFileFormat = outFileFormat.Substring(index + 1); } else { targetDir = string.Format(@"{0}\{1}", artistDir, albumDir); } targetDir = Util.MakeValidFolderName(targetDir); targetDir = string.Format(@"{0}\{1}", _musicDir, targetDir); log.Debug("Rip: Using Target Folder: {0}", targetDir); try { if (!Directory.Exists(targetDir)) { Directory.CreateDirectory(targetDir); } } catch (Exception ex) { SetStatusLabel(localisation.ToString("Conversion", "ErrorDirectory")); log.Error("Error creating Ripping directory: {0}. {1}", targetDir, ex.Message); return; } log.Debug("Rip: Selected CD Drive: {0}", _selectedCDRomDrive); int selectedDriveID = 0; try { // User may change to a different drive while ripping selectedDriveID = CurrentDriveID; log.Debug("Rip: Selected drive id: {0}", selectedDriveID); } catch (Exception) { log.Debug("Rip: Error setting the drive id. Fallback to drive #0"); selectedDriveID = 0; } // Lock the Door BassCd.BASS_CD_Door(CurrentDriveID, BASSCDDoor.BASS_CD_DOOR_LOCK); foreach (DataGridViewRow row in dataGridViewRip.Rows) { // Reset the Status field to 0 row.Cells[1].Value = 0; } _currentRow = -1; foreach (DataGridViewRow row in dataGridViewRip.Rows) { // when checking and unchecking a row, we have the DBNull value if (row.Cells[0].Value == null || row.Cells[0].Value == DBNull.Value) { continue; } if ((int)row.Cells[0].Value == 0) { continue; } SetStatusLabel(localisation.ToString("Conversion", "Ripping")); _currentRow = row.Index; CDTrackDetail track = bindingList[selectedDriveID][_currentRow]; int stream = BassCd.BASS_CD_StreamCreate(selectedDriveID, row.Index, BASSFlag.BASS_STREAM_DECODE); if (stream == 0) { log.Error("Error creating stream for Audio Track {0}. Error: {1}", _currentRow, Enum.GetName(typeof(BASSError), Bass.BASS_ErrorGetCode())); continue; } log.Info("Ripping Audio CD Track{0} - {1}", row.Index + 1, track.Title); _outFile = outFileFormat; _outFile = _outFile.Replace("<O>", artistDir); _outFile = _outFile.Replace("<B>", albumDir); _outFile = _outFile.Replace("<G>", tbGenre.Text); _outFile = _outFile.Replace("<Y>", tbYear.Text); _outFile = _outFile.Replace("<A>", track.Artist); _outFile = _outFile.Replace("<K>", track.Track.ToString().PadLeft(Options.MainSettings.NumberTrackDigits, '0')); _outFile = _outFile.Replace("<T>", track.Title); _outFile = Util.MakeValidFileName(_outFile); _outFile = string.Format(@"{0}\{1}", targetDir, _outFile); _outFile = audioEncoder.SetEncoder(encoder, _outFile); if (audioEncoder.StartEncoding(stream) != BASSError.BASS_OK) { log.Error("Error starting Encoder for Audio Track {0}. Error: {1}", _currentRow, Enum.GetName(typeof(BASSError), Bass.BASS_ErrorGetCode())); } dataGridViewRip.Rows[_currentRow].Cells[1].Value = 100; Bass.BASS_StreamFree(stream); log.Info("Finished Ripping Audio CD Track{0}", _currentRow + 1); try { // Now Tag the encoded File File file = File.Create(_outFile); file.Tag.AlbumArtists = new[] { tbAlbumArtist.Text }; file.Tag.Album = tbAlbum.Text; file.Tag.Genres = new[] { tbGenre.Text }; file.Tag.Year = tbYear.Text == string.Empty ? 0 : Convert.ToUInt32(tbYear.Text); file.Tag.Performers = new[] { track.Artist }; file.Tag.Track = (uint)track.Track; file.Tag.Title = track.Title; file = Util.FormatID3Tag(file); file.Save(); } catch (Exception ex) { log.Error("Error tagging encoded file {0}. Error: {1}", _outFile, ex.Message); } } } catch (Exception ex) { log.Error("Rip: Exception: {0} {1}", ex.Message, ex.StackTrace); } _currentRow = -1; SetStatusLabel(localisation.ToString("Conversion", "RippingFinished")); Options.MainSettings.RipTargetFolder = _musicDir; Options.MainSettings.RipEncoder = encoder; // Unlock the Drive and open the door, if selected BassCd.BASS_CD_Door(CurrentDriveID, BASSCDDoor.BASS_CD_DOOR_UNLOCK); if (Options.MainSettings.RipEjectCD) { BassCd.BASS_CD_Door(CurrentDriveID, BASSCDDoor.BASS_CD_DOOR_OPEN); } // Activate the target Folder, if selected if (Options.MainSettings.RipActivateTargetFolder) { _main.CurrentDirectory = targetDir; _main.TreeView.RefreshFolders(); _main.Ribbon.CurrentTabPage = _main.TabTag; _main.TracksGridView.Show(); if (_main.SplitterRight.IsCollapsed && !Options.MainSettings.RightPanelCollapsed) { _main.SplitterRight.ToggleState(); } _main.RefreshTrackList(); } log.Trace("<<<"); }
public async Task SearchMusic(string path) { var context = new BlogDBContext(); var file = new FileInfo(path); TagFile tagLibFile = null; try { // Прочитаме музикалния файл. tagLibFile = TagFile.Create(path); } catch (Exception) { // Ако не можем да го прочетем отиваме на следващия. return; } using (tagLibFile) { BandEF band = null; Song song = null; AlbumEF album = null; var tag = tagLibFile.Tag; // Взимаме името на бандата. var bandName = tag.FirstAlbumArtist ?? tag.FirstPerformer ?? tag.FirstComposer ?? "Unknown"; // Ако tag.Title е null взимаме името на файла. if (tag.Title is null) { tag.Title = Path.GetFileNameWithoutExtension(file.Name); } // Взимаме името на албума. var albumName = tag.Album ?? "Unknown"; song = context.Songs.FirstOrDefault(s => s.Name == tag.Title); // Опитваме да видим дали има песен със същото име. // Ако има такава песен отиваме на следващата. if (song != null) { return; } // Ако няма банда с това име, създаваме нова. band = context.Bands.FirstOrDefault(f => f.Name == bandName); if (band is null) { band = new BandEF { Name = bandName }; MainViewModel.Collection.Bands.Add(new Band(bandName)); context.Bands.Add(band); } // Ако няма албум с това име, създаваме нов. album = context.Albums.FirstOrDefault(f => f.Name == albumName); if (album is null) { album = new AlbumEF { Name = albumName }; MainViewModel.Collection.Albums.Add(new Album(albumName)); context.Albums.Add(album); } //Създаваме песента с нейната информация. song = new Song { Name = tag.Title, Duration = tagLibFile.Properties.Duration, Location = file.FullName, Volume = GetSongVolume(path) }; MainViewModel.Collection.Songs.Add(song); // Добавяме песента към SQL базата данни. context.Songs.Add(song); // Запазваме песента. await context.SaveChangesAsync(); // SQL създава ID на песента и я взимаме обратно. song = context.Songs.FirstOrDefault(f => f.Name == song.Name); // Добавяме албум с тази песен. context.AlbumsSongs.Add(new AlbumSongsEF { AlbumID = context.Albums.FirstOrDefault(f => f.Name == albumName).ID, SongID = song.ID }); // Добавяме банда с тази песен. context.BandsSongs.Add(new BandSongsEF { BandID = context.Bands.FirstOrDefault(f => f.Name == bandName).ID, SongID = song.ID }); await context.SaveChangesAsync(); } }
private void ProcessTrack(IDBClient db, string file) { // open the file using taglib try { // work out the compression type from the extension var compression = Compression.Lossy; if (AudioConstants.SUPPORTED_LOSSLESS.Contains(Path.GetExtension(file))) { compression = Compression.Lossless; } File musicFile = File.Create(file); // check whether or not the tag information is valid if (null == musicFile.Tag.Album || null == musicFile.Tag.Title) { _log.Error("Invalid tag information for: " + file); } else { // retrieve the album artist first if (null == _albumArtist) { // find the artist that should be for this album _albumArtist = Database.RetrieveArtistByName(db, musicFile.Tag.AlbumArtists[0]); // check if we have an existing album artist if (null == _albumArtist) { // if not, create one _albumArtist = new Artist(musicFile.Tag.AlbumArtists[0]); } } // have an album to work with if (null == _theAlbum) { // we'll attempt to find an album to add it to _theAlbum = Database.RetrieveAlbumByName(db, musicFile.Tag.Album, compression); // if there isn't an existing album if (null == _theAlbum) { // create a new album _theAlbum = new Album(musicFile.Tag.Album, _albumArtist, musicFile.Tag.FirstGenre, (int)musicFile.Tag.Year, compression); } } else { // make sure we have the right album if (_theAlbum.Title != musicFile.Tag.Album) { // we'll attempt to find an album to add it to or create a new one _theAlbum = Database.RetrieveAlbumByName(db, musicFile.Tag.Album, compression) ?? new Album(musicFile.Tag.Album, _albumArtist, musicFile.Tag.FirstGenre, (int)musicFile.Tag.Year, compression); // if there isn't an existing album } } // initialise the output track Track theTrack; var trackArtists = new List <Artist>(); // special case for tracks that have more than one artist if (musicFile.Tag.Performers.Count() > 1) { foreach (var artist in musicFile.Tag.Performers) { // we'll try with the album artist first var performer = _albumArtist; if (artist != _albumArtist.Name) { performer = Database.RetrieveArtistByName(db, artist) ?? new Artist(artist); } trackArtists.Add(performer); } } else { // we'll try with the album artist first if (musicFile.Tag.FirstPerformer == _albumArtist.Name) { trackArtists.Add(_albumArtist); } else { var performer = Database.RetrieveArtistByName(db, musicFile.Tag.FirstPerformer) ?? new Artist(musicFile.Tag.FirstPerformer); trackArtists.Add(performer); } // check for a track in the local object instead of hitting the DB try { // TODO not sure if this will work with the multiple artists now _theAlbum.Tracks.First( x => (x.TrackNumber == (int)musicFile.Tag.Track && x.Title == musicFile.Tag.Title)); } catch (InvalidOperationException) {} } // update the running tally foreach (var artist in trackArtists) { int result = 0; if (_tally.ContainsKey(artist)) { result = _tally[artist]; } if (0 == result) { _tally.Add(artist, 1); } else { _tally[artist] = ++result; } } // create a new track theTrack = new Track((int)musicFile.Tag.Track, trackArtists, _theAlbum, musicFile.Properties.Duration, musicFile.Tag.Title, file); // add the new track to the album _theAlbum.AddTrack(theTrack); // update the reference in the DB Database.UpdateAddTrack(db, theTrack); } } catch (ArgumentOutOfRangeException e) { _log.Error("Taglib had problem reading: " + file, e); return; } catch (Db4oException e) { _log.Error("DB problem when processing track: " + file, e); } catch (IOException e) { _log.Error("File IO problem when processing track: " + file, e); } }
public async Task DownloadTrack(MusixSongResult Track, string OutputDirectory, AudioEffectStack Effects = null, CancellationToken cancellationToken = default) { int Steps; int Step = 0; if (Effects == null) { Steps = 9; } else { Steps = 9 + Effects.EffectCount; } TryCallback(Step, Steps, "Starting Download", Track); if (cancellationToken.IsCancellationRequested) { return; } bool HasEffects = Effects != null; if (HasEffects) { Console.WriteLine("Has Effects"); if (string.IsNullOrEmpty(Effects.AudioCachePath)) { Effects.AudioCachePath = AudioCache; } } // Step 1 Step++; TryCallback(Step, Steps, "Preparing Download", Track); Console.WriteLine("Start Download"); if (!Track.HasVideo) { Console.WriteLine("No Vid"); } if (!Track.HasVideo) { return; } string SourceAudio = Path.Combine(AudioCache, $"audio_source_{DateTime.Now.Ticks}"); string AlbumCover = Path.Combine(ImageCachePath, $"cover_{DateTime.Now.Ticks}.jpg"); string OutputFile = Path.Combine(OutputDirectory, FileHelpers.ScrubFileName($"{Track.SpotifyTrack.Artists[0].Name} - {Track.SpotifyTrack.Name.Replace("?", "").Trim(' ')}.mp3")); string MidConversionFile = Path.Combine(AudioCache, FileHelpers.ScrubFileName($"MidConversion_{DateTime.Now.Ticks}.mp3")); // Step 2 Step++; TryCallback(Step, Steps, "Aquiring streams", Track); StreamManifest StreamData = await YouTube.Videos.Streams.GetManifestAsync(Track.YoutubeVideo.Id); if (cancellationToken.IsCancellationRequested) { return; } // Step 3 Step++; TryCallback(Step, Steps, "Sorting Streams", Track); List <AudioOnlyStreamInfo> AudioStreams = StreamData.GetAudioOnlyStreams().ToList(); AudioStreams.OrderBy(dat => dat.Bitrate); if (AudioStreams.Count() == 0) { Console.WriteLine("No Streams"); } if (AudioStreams.Count() == 0) { return; } IAudioStreamInfo SelectedStream = AudioStreams[0]; // Step 4 Step++; TryCallback(Step, Steps, "Starting downloads", Track); if (cancellationToken.IsCancellationRequested) { return; } //Task AudioDownloadTask = new Task(async () => await YouTube.Videos.Streams.DownloadAsync(SelectedStream, SourceAudio)); var req = WebRequest.CreateHttp(SelectedStream.Url); req.Method = "GET"; using (var resp = req.GetResponse()) using (var network = resp.GetResponseStream()) using (var fs = new FileStream(SourceAudio, FileMode.OpenOrCreate, FileAccess.ReadWrite)) { Console.WriteLine("Downloading"); await network.CopyToAsync(fs); Console.WriteLine("flushing"); await fs.FlushAsync(); Console.WriteLine("done"); } WebClient WebCl = new WebClient(); Step++; TryCallback(Step, Steps, "Starting", Track); SpotifyImage Cover = Track.SpotifyTrack.Album.Images[0]; var CoverDownloadTask = new Task(() => { Console.WriteLine("Downloading Cover"); WebCl.DownloadFile(new Uri(Cover.Url), AlbumCover); } ); CoverDownloadTask.Start(); Step++; TryCallback(Step, Steps, "Waiting for downloads", Track); if (cancellationToken.IsCancellationRequested) { return; } //if (!AudioDownloadTask.IsCompleted) //{ // Console.WriteLine("Waiting on artwork..."); // CoverDownloadTask.Wait(); //} if (cancellationToken.IsCancellationRequested) { return; } //if (!AudioDownloadTask.IsCompleted) //{ // Console.WriteLine("Waiting on audio..."); // AudioDownloadTask.Wait(); // Console.WriteLine("Download Complete."); //} Thread.Sleep(100); if (cancellationToken.IsCancellationRequested) { return; } string ConversionFile = OutputFile; if (HasEffects) { ConversionFile = MidConversionFile; } if (File.Exists(OutputFile)) { File.Delete(OutputFile); } if (File.Exists(ConversionFile)) { File.Delete(ConversionFile); } Step++; TryCallback(Step, Steps, "Transcoding audio to mp3", Track); // Step 8 Console.WriteLine("Starting Conversion..."); await ConversionsProvider.Convert(SourceAudio, ConversionFile); Console.WriteLine("Conversion Complete."); // Step 9 if (cancellationToken.IsCancellationRequested) { return; } if (HasEffects) { Step++; int InternalStep = Step; TryCallback(Step, Steps, "Applying audio effects", Track); Effects.ApplyEffects(ConversionFile, OutputFile, (step, stepmax, status, download) => { step++; TryCallback(Step, Steps, status, Track); }, cancellationToken); } if (cancellationToken.IsCancellationRequested) { return; } Step++; TryCallback(Step, Steps, "Applying ID3 metadata tags", Track); // Step 10 TagLib.Id3v2.Tag.DefaultVersion = 3; TagLib.Id3v2.Tag.ForceDefaultVersion = true; TagLibFile TLF = TagLibFile.Create(OutputFile); TagLibPicture Pic = new TagLibPicture(AlbumCover); TagLib.Id3v2.AttachedPictureFrame Frame = new TagLib.Id3v2.AttachedPictureFrame(Pic) { MimeType = System.Net.Mime.MediaTypeNames.Image.Jpeg }; Pic.Type = TagLib.PictureType.FrontCover; TagLib.IPicture[] Pics = { Pic }; TLF.Tag.Pictures = Pics; TLF.Tag.Title = Track.SpotifyTrack.Name.Split('-')[0].Trim(' '); TLF.Tag.Album = Track.SpotifyTrack.Album.Name; TLF.Tag.AlbumArtists = Track.SpotifyTrack.Album.Artists.CastEnumerable(x => x.Name).ToArray(); TLF.Tag.Disc = (uint)Track.SpotifyTrack.DiscNumber; TLF.Tag.AlbumSort = Track.SpotifyTrack.Album.AlbumType; DateTime?DT = GetDate(Track.SpotifyTrack.Album.ReleaseDate); if (DT.HasValue) { TLF.Tag.Year = (uint)DT.Value.Year; } if (cancellationToken.IsCancellationRequested) { return; } TLF.Save(); // Clean Up // Step 11 Step++; TryCallback(Step, Steps, "Cleaning up", Track); WebCl.Dispose(); TLF.Dispose(); Console.WriteLine("Done."); OnMusixDownloadComplete?.Invoke(Track); }
static void HandleDirectory(DirectoryInfo indir, DirectoryInfo outdir) { foreach (DirectoryInfo subdir in indir.GetDirectories()) { //if (!subdir.Name.StartsWith("0-")) { HandleDirectory(subdir, outdir); } } foreach (FileInfo fi in indir.GetFiles("*.flac")) { string fullname = fi.FullName; if (fullname.Length > 260) { Console.WriteLine("Filename too long: " + fullname); continue; } File f = File.Create(fi.FullName); if (string.IsNullOrEmpty(f.Tag.Album)) { continue; } string ogAlbum = f.Tag.Album; string ogTitle = f.Tag.Title; string album = ogAlbum.Replace(':', '\uFF1A').Replace('\"', '\uFF02').Replace('/', '\uFF0F').Replace('?', '\uFF1F').Replace('|', '\uFF5C').Replace('/', '\uFF0F').Trim(); string title = ogTitle.Replace(':', '\uFF1A').Replace('\"', '\uFF02').Replace('/', '\uFF0F').Replace('?', '\uFF1F').Replace('|', '\uFF5C').Replace('/', '\uFF0F').Trim(); uint disc = f.Tag.Disc; uint trackNo = f.Tag.Track; if (album.StartsWith(".")) { album = album.Replace('.', '.'); } DirectoryInfo albumOutDir = new DirectoryInfo(Path.Combine(outdir.FullName, album + pathSeperator)); EnsureDirectoryExists(albumOutDir); FileInfo coverOutFileInfo = new FileInfo(Path.Combine(albumOutDir.FullName, "folder.jpg")); if (!coverOutFileInfo.Exists) { var pictures = f.Tag.Pictures; if (pictures.Length > 0) { Console.WriteLine("Writing album art for: {0}", album); var picture = pictures[0]; MemoryStream ms = new MemoryStream(picture.Data.Data); Bitmap bmp = new Bitmap(ms); bmp.Save(coverOutFileInfo.FullName, ImageFormat.Jpeg); bmp.Dispose(); ms.Dispose(); } } f.Dispose(); string outFileName = string.Format("{0}{1}{2:00} {3}.ogg", albumOutDir, disc != 0 ? disc.ToString() + "." : "", trackNo, title); outFileName = outFileName.Replace('\"', '\uFF02'); outFileName = outFileName.Replace('?', '\uFF1F'); outFileName = outFileName.Replace('<', '\uFF1C'); outFileName = outFileName.Replace('>', '\uFF1E'); outFileName = outFileName.Replace('*', '\uFF0A'); FileInfo outFileInfo = new FileInfo(outFileName); if (!outFileInfo.Exists) { if (!outFileInfo.Directory.Exists) { EnsureDirectoryExists(outFileInfo.Directory); } string oggencSwitches = null; string oggencSwitchesFilename = Path.Combine(indir.FullName, "oggenc2.conf"); if (System.IO.File.Exists(oggencSwitchesFilename)) { oggencSwitches = System.IO.File.ReadAllText(oggencSwitchesFilename); } Console.WriteLine("Encoding:" + outFileInfo.Name); Process p = new Process(); while (outFileName.Length > 255) { outFileName = title.Substring(0, title.Length - 1); outFileName = string.Format("{0}{1}{2:00} {3}.ogg", albumOutDir, disc != 0 ? disc.ToString() + "." : "", trackNo, title); } p.StartInfo.Arguments = string.Format("{2} \"{0}\" -o \"{1}\"", fi.FullName, outFileName, oggencSwitches); p.StartInfo.FileName = encoder; p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardOutput = true; p.Start(); p.WaitForExit(); outFileInfo.Refresh(); if (!outFileInfo.Exists) { title = string.Format("Track {0}", trackNo); outFileName = string.Format("{0}{1}{2:00} {3}.ogg", albumOutDir, disc != 0 ? disc.ToString() + "." : "", trackNo, title); if (!new FileInfo(outFileName).Exists) { p.StartInfo.Arguments = string.Format("{2} \"{0}\" -o \"{1}\"", fi.FullName, outFileName, oggencSwitches); p.Start(); p.WaitForExit(); } } } else { Console.WriteLine("Skipping:" + outFileInfo.Name); } } }
private File LoadSong(string path) { _logController.LoadSong(path); return(File.Create(path)); }
public static Music CreateFromFile(FileInfo file) { var tfile = File.Create(file.FullName); return(new Music(tfile, file)); }
private void OnFoundFile(List <string> path, string file) { File metaData = null; try { metaData = File.Create(file); } catch (Exception e) { return; } Album album = null; if (!metaData.Tag.IsEmpty && !string.IsNullOrEmpty(metaData.Tag.Album)) { album = _workingAlbums.FirstOrDefault(searchedAlbum => searchedAlbum.Name == metaData.Tag.Album) ?? _albums.FirstOrDefault(searchedAlbum => searchedAlbum.Name == metaData.Tag.Album); if (album != null && album.Cover == null && metaData.Tag.Pictures.Length > 0) { lock (album) { album.Cover = CreateCover(metaData); } } if (album == null) { lock (_albums) { _workingAlbums.Add(album = new Album { Name = metaData.Tag.Album, Cover = CreateCover(metaData) }); } } } List <Artist> artists = new List <Artist>(); if (!metaData.Tag.IsEmpty) { foreach (var performer in metaData.Tag.Performers) { var artist = _workingArtists.FirstOrDefault(searchedArtist => searchedArtist.Name == performer) ?? _artists.FirstOrDefault(searchedArtist => searchedArtist.Name == performer); if (artist == null) { lock (_artists) _workingArtists.Add(artist = new Artist { Name = performer }); } artists.Add(artist); } } { if ((_workingTracks.FirstOrDefault(track => track.Path == file) ?? _tracks.FirstOrDefault(track => track.Path == file)) != null) { return; } } { TrackUserTag userTag = null; Track track = new Track { Album = album, Artists = artists, Name = !metaData.Tag.IsEmpty && !string.IsNullOrEmpty(metaData.Tag.Title) ? metaData.Tag.Title : Path.GetFileNameWithoutExtension(file), Duration = metaData.Properties.Duration, UserTag = new TrackUserTag(), Genres = new List <string>(metaData.Tag.Genres), RelativePaths = path, Path = file }; _workingTracks.Add(track); if (album != null) { lock (album) { album.Tracks.Add(track); foreach (var artist in artists) { album.Artists.Add(artist); lock (artist) artist.Albums.Add(album); } } } foreach (var artist in artists) { lock (artist) artist.Singles.Add(track); } } }
private void GetTracksFromFolders() { var extensions = new List <string> { ".mp3", ".flac" }; var index = Math.Max(tracks.Count, 1); foreach ( var files in folders .Select(folder => Directory .GetFiles(folder, "*.*", SearchOption.AllDirectories) .Where(f => extensions.IndexOf(Path.GetExtension(f)) >= 0))) { foreach (var file in files) { var artists = ""; var album = ""; var title = ""; int duration; try { var tagFile = File.Create(file); duration = (int)tagFile.Properties.Duration.TotalMilliseconds; artists = string.Join(", ", tagFile.Tag.Performers); album = tagFile.Tag.Album ?? ""; title = tagFile.Tag.Title ?? ""; } catch (Exception) { try { var extension = file.Split('.').Last(); if (extension.Equals("mp3")) { var reader = new Mp3FileReader(file); duration = (int)reader.TotalTime.TotalMilliseconds; } else { var reader = new FlacReader(file); duration = (int)reader.TotalTime.TotalMilliseconds; } } catch (Exception) { continue; } } if (duration > 10 * 60 * 1000) { continue; } if (tracks.ContainsKey(file)) { continue; } var track = new Track { Id = index++, IsSpotifyTrack = false, HasMetaData = title.Length != 0, TrackName = title, Artist = artists, Album = album, TrackPath = file, TotalTime = duration, Location = file }; tracks.Add(file, track); } } }
private void ConversionThread() { if (_main.InvokeRequired) { ThreadSafeConvertDelegate d = ConversionThread; _main.Invoke(d); return; } log.Trace(">>>"); string rootFolder = _main.EncoderOutputDirectory; if (string.IsNullOrEmpty(rootFolder)) { rootFolder = Options.MainSettings.RipTargetFolder; } string encoder = null; if (_main.EncoderCombo.SelectedItem != null) { encoder = (string)(_main.EncoderCombo.SelectedItem as Item).Value; } if (encoder == null) { return; } try { if (!Directory.Exists(rootFolder) && !string.IsNullOrEmpty(rootFolder)) { Directory.CreateDirectory(rootFolder); } } catch (Exception ex) { MessageBox.Show(localisation.ToString("Conversion", "ErrorDirectory"), localisation.ToString("message", "Error_Title"), MessageBoxButtons.OK); log.Error("Error creating Conversion output directory: {0}. {1}", rootFolder, ex.Message); return; } foreach (DataGridViewRow row in dataGridViewConvert.Rows) { // Reset the Status field to 0 row.Cells[0].Value = 0; } _currentRow = -1; foreach (DataGridViewRow row in dataGridViewConvert.Rows) { _currentRow = row.Index; ConversionData track = bindingList[_currentRow]; string inputFile = track.Track.FullFileName; string outFile = Util.ReplaceParametersWithTrackValues(Options.MainSettings.RipFileNameFormat, track.Track); outFile = Path.Combine(rootFolder, outFile); string directoryName = Path.GetDirectoryName(outFile); // Now check the validity of the directory if (!Directory.Exists(directoryName)) { try { Directory.CreateDirectory(directoryName); } catch (Exception e1) { log.Error("Error creating folder: {0} {1]", directoryName, e1.Message); row.Cells[0].Value = localisation.ToString("message", "Error"); row.Cells[0].ToolTipText = String.Format("{0}: {1}", localisation.ToString("message", "Error"), e1.Message); continue; // Process next row } } outFile = audioEncoder.SetEncoder(encoder, outFile); UpdateNewFileName(outFile); if (inputFile == outFile) { row.Cells[0].ToolTipText = String.Format("{0}: {1}", inputFile, localisation.ToString("Conversion", "SameFile")); log.Error("No conversion for {0}. Output would overwrite input", inputFile); continue; } int stream = Bass.BASS_StreamCreateFile(inputFile, 0, 0, BASSFlag.BASS_STREAM_DECODE); if (stream == 0) { row.Cells[0].ToolTipText = String.Format("{0}: {1}", inputFile, localisation.ToString("Conversion", "OpenFileError")); log.Error("Error creating stream for file {0}. Error: {1}", inputFile, Enum.GetName(typeof(BASSError), Bass.BASS_ErrorGetCode())); continue; } log.Info("Convert file {0} -> {1}", inputFile, outFile); if (audioEncoder.StartEncoding(stream) != BASSError.BASS_OK) { row.Cells[0].ToolTipText = String.Format("{0}: {1}", inputFile, localisation.ToString("Conversion", "EncodingFileError")); log.Error("Error starting Encoder for File {0}. Error: {1}", inputFile, Enum.GetName(typeof(BASSError), Bass.BASS_ErrorGetCode())); Bass.BASS_StreamFree(stream); continue; } dataGridViewConvert.Rows[_currentRow].Cells[0].Value = 100; Bass.BASS_StreamFree(stream); try { // Now Tag the encoded File File tagInFile = File.Create(inputFile); File tagOutFile = File.Create(outFile); tagOutFile.Tag.AlbumArtists = tagInFile.Tag.AlbumArtists; tagOutFile.Tag.Album = tagInFile.Tag.Album; tagOutFile.Tag.Genres = tagInFile.Tag.Genres; tagOutFile.Tag.Year = tagInFile.Tag.Year; tagOutFile.Tag.Performers = tagInFile.Tag.Performers; tagOutFile.Tag.Track = tagInFile.Tag.Track; tagOutFile.Tag.TrackCount = tagInFile.Tag.TrackCount; tagOutFile.Tag.Title = tagInFile.Tag.Title; tagOutFile.Tag.Comment = tagInFile.Tag.Comment; tagOutFile.Tag.Composers = tagInFile.Tag.Composers; tagOutFile.Tag.Conductor = tagInFile.Tag.Conductor; tagOutFile.Tag.Copyright = tagInFile.Tag.Copyright; tagOutFile.Tag.Disc = tagInFile.Tag.Disc; tagOutFile.Tag.DiscCount = tagInFile.Tag.DiscCount; tagOutFile.Tag.Lyrics = tagInFile.Tag.Lyrics; tagOutFile.Tag.Pictures = tagInFile.Tag.Pictures; tagOutFile = Util.FormatID3Tag(tagOutFile); tagOutFile.Save(); } catch (Exception ex) { log.Error("Error tagging encoded file {0}. Error: {1}", outFile, ex.Message); } } Options.MainSettings.LastConversionEncoderUsed = encoder; _currentRow = -1; log.Trace("<<<"); }
private void RebuildFromFolder(SubscriptionInfo subscriptionInfo, string folderPath, bool restricted, int startPercent = 0, int endPercent = 100) { if (folderPath == null) { throw new ArgumentNullException(nameof(folderPath)); } using (IDbConnection db = _dbConnectionFactory.Open()) { DirectoryInfoBase directoryInfo = _fileSystem.DirectoryInfo.FromDirectoryName(folderPath); FileInfoBase[] files = directoryInfo.GetFiles("*.mp3", SearchOption.AllDirectories); int index = 0; foreach (IGrouping <string, FileInfoBase> albumFiles in files.GroupBy(f => f.DirectoryName)) { using (IDbTransaction transaction = db.OpenTransaction()) { _logger.Debug("Fetching album"); DbAlbum album = db.Single <DbAlbum>(a => a.Path == albumFiles.Key); foreach (FileInfoBase file in albumFiles) { int progress = (int)Math.Round((index + 1) / (double)files.Length * (endPercent - startPercent)) + startPercent; PublishProgress(subscriptionInfo, progress); _logger.DebugFormat("Processing file {0}", file.FullName); DbRecording recording; bool saveTagFile = false; _logger.Debug("Reading tag file"); using (File tagFile = File.Create(_fileAbstractionFactory(file.FullName, true))) { string recordingId = tagFile.GetCustomField(SoundWordsRecordingIdField); if (recordingId != null) { _logger.Debug("Fetching recording"); recording = db.Single <DbRecording>(r => r.Uid == recordingId) ?? new DbRecording { Uid = recordingId }; } else { recording = new DbRecording { Uid = Guid.NewGuid().ToString("N") }; saveTagFile = true; tagFile.SetCustomField(SoundWordsRecordingIdField, recording.Uid); } if (album == null) { string uid = tagFile.GetCustomField(SoundWordsAlbumIdField) ?? Guid.NewGuid().ToString("N"); album = new DbAlbum { Uid = uid, Name = (tagFile.Tag.Album ?? "Ukjent").Trim(), Path = albumFiles.Key, Restricted = restricted }; } UpdateAttachments(albumFiles.Key, album); if (album.Id != 0) { _logger.Debug("Saving album"); db.Update(album); } else { _logger.Debug("Creating album"); album.Id = db.Insert(album, true); } if (tagFile.GetCustomField(SoundWordsAlbumIdField) != album.Uid) { tagFile.SetCustomField(SoundWordsAlbumIdField, album.Uid); saveTagFile = true; } recording.AlbumId = album.Id; recording.Title = (tagFile.Tag.Title ?? "Ukjent").Trim(); recording.Track = (ushort)tagFile.Tag.Track; recording.Comment = tagFile.Tag.Comment; recording.Year = tagFile.Tag.Year != 0 ? (ushort?)tagFile.Tag.Year : null; recording.Path = file.FullName; recording.Restricted = restricted; if (recording.Id == 0) { _logger.DebugFormat("Creating recording: {0}", recording.Dump()); recording.Id = db.Insert(recording, true); } else { _logger.DebugFormat("Saving recording: {0}", recording.Dump()); db.Update(recording); } db.Delete <DbRecordingSpeaker>(rs => rs.RecordingId == recording.Id); foreach (string performer in tagFile.Tag.Performers) { _logger.DebugFormat($"Creating speaker {performer}"); NameInfo nameInfo = performer.ToNameInfo(); DbSpeaker speaker = db.Single <DbSpeaker>(s => s.FirstName == nameInfo.FirstName && s.LastName == nameInfo.LastName); if (speaker == null) { speaker = new DbSpeaker { Uid = Guid.NewGuid().ToString("N"), FirstName = nameInfo.FirstName, LastName = nameInfo.LastName }; speaker.Id = db.Insert(speaker, true); } if (!db.Exists <DbRecordingSpeaker>(rs => rs.RecordingId == recording.Id && rs.SpeakerId == speaker.Id)) { db.Insert(new DbRecordingSpeaker { RecordingId = recording.Id, SpeakerId = speaker.Id }); } } if (saveTagFile) { _logger.Debug("Writing ID tag data"); tagFile.Save(); } } index++; } _logger.Info("Committing transaction"); transaction.Commit(); } } } }
public void MoveTo(string path) { System.IO.File.Move(_content.Name, path); _content = File.Create(path); }
public async Task <bool> AddSong(IFormFile file) { await using (Stream stream = file.OpenReadStream()) { using var binaryReader = new BinaryReader(stream); var fileContent = binaryReader.ReadBytes((int)file.Length); var str = Encoding.Default.GetString(fileContent); //await this.UploadFile(file.ContentDisposition); var filePath = @"songstorage/testmp3.mp3"; using (var fileStream = new FileStream(filePath, FileMode.Create)) { await file.CopyToAsync(fileStream); } TagLibFile.IFileAbstraction iFile = new TagLibFile.LocalFileAbstraction(filePath); var mp3 = TagLibFile.Create(iFile); var artistName = mp3.Tag.Performers[0]; var albumName = mp3.Tag.Album; var albumNumber = mp3.Tag.Track; //todo add album art //create new artist / album if it doesnt exist yet var artist = _artistManager.FindByName(artistName) ?? new Artist() { Name = artistName }; var album = _albumManager.FindByName(albumName) ?? new Album() { Artist = artist, Name = albumName }; //TODO fix duration var song = new Song(mp3.Tag.Title, artist, album, mp3.Properties.Duration.Seconds, (int)albumNumber); _songManager.Add(song); // var extension = Path.GetExtension(file.FileName); // var folderPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "MusifyStorage", artistName, albumName); // var fileName = albumNumber + " - " + mp3.Tag.Title; // var fullPath = Path.Combine(folderPath, fileName + extension); var fileInfo = new FileInfo(song.FilePath); if (!Directory.Exists(fileInfo.DirectoryName)) { Directory.CreateDirectory(fileInfo.DirectoryName); } using (var fileStream = new FileStream(fileInfo.FullName, FileMode.Create)) { await file.CopyToAsync(fileStream); } Console.WriteLine(fileInfo.FullName); } return(true); }
public async Task ScanMusicFolder(string path) { var files = Directory.EnumerateFiles(path, "*.*", SearchOption.AllDirectories); var albumDictionary = new Dictionary <int, Album>(); using (var dbLock = await LockDatabaseAsync()) { var db = Database; var artistsCollection = db.GetCollection <Artist>(Artist.CollectionName); var albumsCollection = db.GetCollection <Album>(Album.CollectionName); var tracksCollection = db.GetCollection <Track>(Track.CollectionName); foreach (var file in files.Select(x => new FileInfo(x).FullName)) { if (!SupportedFileExtensions.Any(x => $".{x}" == Path.GetExtension(file).ToLower())) { continue; } try { using (var tagFile = File.Create(file)) { var tag = tagFile.Tag; if (tag is null) { continue; } var artistName = tag.AlbumArtists.Concat(tag.Artists).FirstOrDefault(); if (artistName is null) { artistName = "Unknown Artist"; } var albumName = tag.Album ?? "Unknown Album"; var trackName = tag.Title ?? "Unknown Track"; // TODO other what to do if we dont know anything about the track, ignore? StatusChanged?.Invoke(this, $"Processing: {artistName}, {albumName}, {trackName}"); var existingArtist = artistsCollection.FindOne(x => x.Name == artistName.Trim()); if (existingArtist is null) { existingArtist = new Artist { Name = artistName }; artistsCollection.Insert(existingArtist); } var existingAlbum = albumsCollection.FindOne(x => x.ArtistId == existingArtist.ArtistId && x.Title == tag.Album.Trim()); var albumAdded = false; if (existingAlbum is null) { albumAdded = true; existingAlbum = new Album { Title = albumName, ArtistId = existingArtist.ArtistId, Artist = existingArtist }; albumsCollection.Insert(existingAlbum); existingArtist.Albums.Add(existingAlbum); artistsCollection.Update(existingArtist); albumDictionary.Add(existingAlbum.AlbumId, existingAlbum); Albums.Add(existingAlbum); } else { if (albumDictionary.ContainsKey(existingAlbum.AlbumId)) { existingAlbum = albumDictionary[existingAlbum.AlbumId]; } else { albumDictionary[existingAlbum.AlbumId] = existingAlbum; } } var existingTrack = tracksCollection.FindOne(x => x.Path == file); if (existingTrack is null) { existingTrack = new Track { Path = new FileInfo(file).FullName, Title = trackName, Album = existingAlbum }; tracksCollection.Insert(existingTrack); existingAlbum.Tracks.Add(existingTrack); albumsCollection.Update(existingAlbum); } else { existingTrack.Album = existingAlbum; } } } catch (Exception e) { } } } }
/// <summary> /// Call this method to play track. Returns false if not playable /// </summary> /// <param name="error"></param> /// <returns></returns> private bool InitializeForPlay(out string error) { if (_initialized) { error = string.Empty; return(true); } if (string.IsNullOrWhiteSpace(_model.Location)) { error = _nonf[4]; return(false); } if (!System.IO.File.Exists(_model.Location)) { error = "file does not exist"; return(false); } try { _v = File.Create(_model.Location); } catch (Exception e) { error = e.Message; return(false); } try { _waveOut = new WaveOut(); } catch (Exception e) { error = e.Message; return(false); } try { _reader = new Mp3FileReader(_model.Location); _waveOut.Init(_reader); //_waveOut.Play(); } catch (Exception e) { error = e.Message; return(false); } if (_v == null) { error = _nonf[0]; return(false); } if (_v.PossiblyCorrupt) { error = _nonf[2]; return(false); // } if (_v.MimeType != "taglib/mp3") { error = _nonf[3]; return(false); } error = "Succesfully initiated player for file"; _initialized = true; return(true); }
/// <summary> /// 修改歌曲信息协程 /// </summary> /// <param name="dirPath"></param> /// <returns></returns> private IEnumerator EditComment(string dirPath) { mCorRunning = true; mIgnoreNum = 0; mAllNum = 0; mFailNum = 0; mDealNum = 0; mMapKeyInfo.Clear(); var pathList = new[] { dirPath }; if (!mIsFile) { //判断单文件还是文件夹 pathList = Directory.GetFiles(dirPath); } var startTime = Time.realtimeSinceStartup; mAllNum = pathList.Length; for (var i = 0; i < pathList.Length; i++) { var path = pathList[i]; if (path.EndsWith("mp3")) { var name = ""; var f = File.Create(path); if (!mTgCover.isOn && f.Tag.Comment.Contains("163")) { //不覆盖 Debug.LogWarning("不覆盖已经有Comment的,跳过:" + f.Tag.Title); mIgnoreNum++; continue; } if (!mTgCoverMatch.isOn && MatchTag.Equals(f.Tag.Description)) { //不覆盖已经准确匹配过的 Debug.LogWarning("不覆盖已经准确匹配过的,跳过:" + f.Tag.Title); mIgnoreNum++; continue; } name = f.Tag.Title.Trim(); if (string.IsNullOrEmpty(name)) { //Tag里面为空就从路径里面获取 name = Path.GetFileNameWithoutExtension(path); // name = path.Substring(path.LastIndexOf("/") + 1); // name = name.Substring(0, name.IndexOf(".")); } Debug.Log("歌曲名字: " + name); if (!string.IsNullOrEmpty(name)) { if (f.Tag.Performers != null && f.Tag.Performers.Length > 0) { //搜索增加名字 name += " " + f.Tag.Performers[0]; } mDealNum++; mTvStatus.text = "正在处理:" + mDealNum + "/" + mAllNum + ",忽略:" + mIgnoreNum + ",失败:" + mFailNum; mLog.Enqueue("正在处理 " + f.Tag.Title); if (mTgDiyUrl.isOn) { //自定义修改 Debug.Log("自定义修改: " + mDiySongID); mMapKeyInfo.Add(path, new SongInfo() { id = mDiySongID, }); } else { yield return(Search(f.Tag, path, name, (songInfo) => { if (songInfo != null) { mMapKeyInfo.Add(path, songInfo); } else { mFailNum++; } f.Dispose(); })); } if (i == pathList.Length - 1 || mMapKeyInfo.Count == DetailNum) { //每20条内容或者最后一条了,就获取详情 Debug.Log("开始获取详情:" + mDealNum); mLog.Enqueue("开始获取详情:" + mDealNum); var idList = new List <int>(); foreach (var keyValuePair in mMapKeyInfo) { idList.Add(keyValuePair.Value.id); } //获取歌曲详情 yield return(GetSongDetail(idList.ToArray(), (songs) => { if (songs != null && songs.Count > 0) { var keyList = mMapKeyInfo.Keys.ToArray(); foreach (var key in keyList) { mMapKeyInfo.TryGetValue(key, out var outInfo); if (outInfo != null) { var isMatch = outInfo.IsMatch; var songInfo = songs.Find(v => v.id == outInfo.id); songInfo.IsMatch = isMatch; //替换搜索的实体为详情得到的实体 mMapKeyInfo[key] = songInfo; } } foreach (var keyValuePair in mMapKeyInfo) { var songInfo = keyValuePair.Value; if (songInfo != null) { var fCache = File.Create(keyValuePair.Key); songInfo.bitrate = fCache.Properties.AudioBitrate * 1000; var comment = JsonMapper.ToJson(songInfo.ToKeyInfo()); fCache.Tag.Comment = "163 key(Don't modify):" + AesUtils.Encrypt("music:" + comment, AesKey); //定义是否完全匹配 fCache.Tag.Description = (songInfo.IsMatch ? MatchTag : ""); fCache.Save(); fCache.Dispose(); var fileName = "/" + Path.GetFileName(keyValuePair.Key); //根据文件名称来删除数据库 mDataDataService?.DeleteRow(fileName); } else { mFailNum++; } } } else { mFailNum += idList.Count; } })); //清空当前歌曲库 mMapKeyInfo.Clear(); } } } } mCorRunning = false; mBtnEdit.GetComponentInChildren <Text>().text = "开始"; yield return(null); Debug.Log("搜索完毕,耗时:" + (Time.realtimeSinceStartup - startTime) + "秒"); mTvStatus.text = "处理完毕:" + mDealNum + "/" + mAllNum + ",忽略:" + mIgnoreNum + ",失败:" + mFailNum; mLog.Enqueue(mTvStatus.text); if (mNeedReOpen) { if (mDealNum > 0) { Debug.Log("需要重启网易云生效"); mLog.Enqueue("请重启网易云生效"); } mDataDataService?.Close(); } }
private void TreatSingleFile(int i, string file, Dictionary <KeyValuePair <string, bool>, AlbumArtistData> localAlbumArtistDatas, Dictionary <KeyValuePair <KeyValuePair <string, AlbumArtistData>, bool>, AlbumData> localAlbumDatas, Dictionary <KeyValuePair <string, bool>, GenreData> localGenreDatas, Dictionary <KeyValuePair <string, bool>, PerformerData> localPerformerDatas) { try { TagFile tagFile = TagFile.Create(file); TrackData track; if (tagFile != null) { if (tagFile.Tag != null) { TagLib.Tag tag = tagFile.Tag; AlbumArtistData albumArtist = localAlbumArtistDatas[new KeyValuePair <string, bool>(_NULL, true)]; AlbumData album = localAlbumDatas[new KeyValuePair <KeyValuePair <string, AlbumArtistData>, bool>(new KeyValuePair <string, AlbumArtistData>(_NULL, albumArtist), true)]; var performers = new List <PerformerData>(); var genres = new List <GenreData>(); var sourceAlbumArtists = new List <string>(); if (tag.AlbumArtists?.Length > 1) { LoadingLogHandler?.BeginInvoke(this, new LoadingLogEventArgs(new LogData($"Multiple album artists for the file : {file}.", LogLevel.Warning), i), null, null); } if (tag.AlbumArtists != null) { sourceAlbumArtists = tag.AlbumArtists.Where(aa => aa != null).ToList(); } if (tag.FirstAlbumArtist != null) { if (!localAlbumArtistDatas.TryGetValue(new KeyValuePair <string, bool>(tag.FirstAlbumArtist, false), out albumArtist)) { albumArtist = new AlbumArtistData(tag.FirstAlbumArtist, false); localAlbumArtistDatas.Add(new KeyValuePair <string, bool>(tag.FirstAlbumArtist, false), albumArtist); } } if (tag.Album != null) { var key = new KeyValuePair <string, AlbumArtistData>(tag.Album, albumArtist); if (!localAlbumDatas.TryGetValue(new KeyValuePair <KeyValuePair <string, AlbumArtistData>, bool>(key, false), out album)) { album = new AlbumData(albumArtist, tag.Album, false); localAlbumDatas.Add(new KeyValuePair <KeyValuePair <string, AlbumArtistData>, bool>(key, false), album); } } if (tag.Performers != null) { foreach (string performer in tag.Performers) { PerformerData performerd = localPerformerDatas[new KeyValuePair <string, bool>(_NULL, true)]; if (performer != null) { if (!localPerformerDatas.TryGetValue(new KeyValuePair <string, bool>(performer, false), out performerd)) { performerd = new PerformerData(performer, false); localPerformerDatas.Add(new KeyValuePair <string, bool>(performer, false), performerd); } } if (!performers.Contains(performerd)) { performers.Add(performerd); } } } if (tag.Genres != null) { foreach (string genre in tag.Genres) { GenreData genred = localGenreDatas[new KeyValuePair <string, bool>(_NULL, true)]; if (genre != null) { if (!localGenreDatas.TryGetValue(new KeyValuePair <string, bool>(genre, false), out genred)) { genred = new GenreData(genre, false); localGenreDatas.Add(new KeyValuePair <string, bool>(genre, false), genred); } } if (!genres.Contains(genred)) { genres.Add(genred); } } } List <byte> frontCoverDatas = ExtractFrontCoverInformations(tag, out string frontCoverMimeType); track = new TrackData(tag.Track, tag.Title ?? _NULL, album, performers, genres, tag.Year, (tagFile.Properties?.Duration).GetValueOrDefault(TimeSpan.Zero), tagFile.Name, sourceAlbumArtists, GetMimeType(tagFile.MimeType), frontCoverMimeType, frontCoverDatas); } else { track = new TrackData(tagFile.Name, (tagFile.Properties?.Duration).GetValueOrDefault(TimeSpan.Zero), localAlbumDatas[new KeyValuePair <KeyValuePair <string, AlbumArtistData>, bool>(new KeyValuePair <string, AlbumArtistData>(_NULL, localAlbumArtistDatas[new KeyValuePair <string, bool>(_NULL, true)]), false)], GetMimeType(tagFile.MimeType)); } } else { track = new TrackData(file, TimeSpan.Zero, localAlbumDatas[new KeyValuePair <KeyValuePair <string, AlbumArtistData>, bool>(new KeyValuePair <string, AlbumArtistData>(_NULL, localAlbumArtistDatas[new KeyValuePair <string, bool>(_NULL, true)]), false)], tagFile.MimeType); } _tracks.Add(track); LoadingLogHandler?.BeginInvoke(this, new LoadingLogEventArgs(new LogData($"The file {file} has been processed.", LogLevel.Information), i), null, null); } catch (Exception exLocal) { LoadingLogHandler?.BeginInvoke(this, new LoadingLogEventArgs(new LogData($"Error while processing {file}.", LogLevel.Error, new KeyValuePair <string, string>("Error message", exLocal.Message)), i), null, null); } }