private void AddMusic(string[] strTemp, string strTitle, string strFileName, string strFilePath) { bool isFolder = false; bool isEmptyFolder = false; FileInfo file = new FileInfo(Path.Combine(strFilePath, strFileName)); Hashtable tags = new Hashtable(); Media objMedia = MediaServices.Get(_strMediaName.Trim(), _mediaType, _path, _cleanTitle, _entityType, _patternType, _useSubFolder, _bGetImage, _bParseNfo, true); if (file.Exists == false && string.IsNullOrWhiteSpace(file.Extension)) { if (Directory.Exists(file.FullName)) { DirectoryInfo folder = new DirectoryInfo(file.FullName); FileInfo[] files = folder.GetFiles("*.mp3", SearchOption.TopDirectoryOnly); files = files.Concat(folder.GetFiles("*.flc", SearchOption.TopDirectoryOnly)).ToArray(); files = files.Concat(folder.GetFiles("*.flac", SearchOption.TopDirectoryOnly)).ToArray(); if (files.Any()) { file = files[0]; isFolder = true; } else { isEmptyFolder = true; } } } if (isEmptyFolder == false) { if (Dal.GetInstance.GetMusics(objMedia.Name, strFilePath, strFileName) == null) { switch (file.Extension) { case ".mp3": IID3v2 objMp3Tag = ID3v2Helper.CreateID3v2(file.FullName); tags.Add("Title", objMp3Tag.Title); if (string.IsNullOrWhiteSpace(objMp3Tag.Album) == false) { tags.Add("Album", objMp3Tag.Album); } if (isFolder == false && objMp3Tag.LengthMilliseconds != null) { tags.Add("Length", objMp3Tag.LengthMilliseconds); } if (objMp3Tag.PictureList.Count > 0) { tags.Add("Cover", objMp3Tag.PictureList[0].PictureData); } tags.Add("Genre", objMp3Tag.Genre); tags.Add("Artist", objMp3Tag.Artist); break; case ".flac": case ".flc": try { FlacTagger objFlacTag = new FlacTagger(file.FullName); tags.Add("Title", objFlacTag.Title); if (string.IsNullOrWhiteSpace(objFlacTag.Album) == false) { tags.Add("Album", objFlacTag.Album); } if (isFolder == false) { tags.Add("Length", objFlacTag.Length); } if (objFlacTag.Arts.Count > 0) { tags.Add("Cover", objFlacTag.Arts[0].PictureData); } tags.Add("Genre", objFlacTag.Genre); tags.Add("Artist", objFlacTag.Artist); break; } //FIX 2.8.9.0 catch (FileFormatException) { break; } } #region Title if (tags.ContainsKey("Title") == false) { if (string.IsNullOrEmpty(strTitle) == false) { strTitle = strTitle.Replace('_', ' '); strTitle = strTitle.Replace(".MP3", ""); strTitle = strTitle.Replace(".Mp3", ""); strTitle = strTitle.Replace(".flac", ""); strTitle = strTitle.Trim(); strTitle = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(strTitle); tags.Add("Title", strTitle); } } #endregion Music objMusic = new Music(); objMusic.Ressources = new List <Ressource>(); objMusic.Genres = new List <Genre>(); objMusic.Title = strTitle; objMusic.AddedDate = DateTime.Now; objMusic.FileName = strFileName; objMusic.FilePath = strFilePath; if (tags.ContainsKey("Album")) { objMusic.Album = tags["Album"].ToString(); if (isFolder == true && string.IsNullOrWhiteSpace(tags["Album"].ToString()) == false) { objMusic.Title = tags["Album"].ToString(); } } if (tags.ContainsKey("Length")) { objMusic.Runtime = tags["Length"] as int?; } objMusic.Media = objMedia; #region Cover if (_bGetImage == true) { RessourcesServices.AddImage(Util.GetLocalImage(objMusic.FilePath, objMusic.FileName, _bFile), objMusic, true); } else { RessourcesServices.AddImage(tags["Cover"] as byte[], objMusic, true); } #endregion bool bExist = false; if (Dal.GetInstance.GetMusics(objMusic.Media.Name, objMusic.FilePath, objMusic.FileName) != null) { bExist = true; } if (bExist == false) { #region ParseNfo if (_bParseNfo == true) { string errorMessage; MusicServices.ParseNfo(objMusic, out errorMessage); } #endregion #region Artist string strArtistFullName = string.Empty; if (tags.ContainsKey("Artist") == true) { if (tags["Artist"] == null) { if (_mapping != null) { strArtistFullName = Util.ConstructString(strTemp, (string[])_mapping["Artist"], _nbrBaseParsing); } } else { strArtistFullName = tags["Artist"] as string; } } #endregion Dal.GetInstance.AddMusic(objMusic); if (tags.ContainsKey("Genre")) { GenreServices.AddGenres(new[] { tags["Genre"] as string }, objMusic, true); } if (strArtistFullName != null && string.IsNullOrWhiteSpace(strArtistFullName.Trim()) == false) { ArtistServices.AddArtist(strArtistFullName, objMusic); } _intAddedItem++; } else { _intNotAddedItem++; } } } }
private static void ConvertSongsInFolder(string path) { if (!Directory.Exists(path)) { return; } DirectoryInfo directoryInfo = new DirectoryInfo(path); List<FileInfo> files = new List<FileInfo>(); files.AddRange(directoryInfo.GetFiles()); files = files.FindAll(delegate(FileInfo f) { return f.Extension.ToLower() == ".flac"; }); int count = 0; foreach (FileInfo file in files) { count++; Console.WriteLine(file.FullName); FlacTagger tags = new FlacTagger(file.FullName); string album = tags.Album; string artist = tags.Artist; string date = tags.Date; string genre = tags.Genre; string title = tags.Title; string trackNumber = tags.TrackNumber; string wavTempName = path; if (wavTempName[wavTempName.Length - 1] != '\\') { wavTempName += "\\"; } wavTempName += System.Guid.NewGuid().ToString("N"); string flacTempName = wavTempName; wavTempName += ".wav"; flacTempName += ".flac"; System.IO.File.Copy(file.FullName, flacTempName); System.Diagnostics.ProcessStartInfo flacProcessStartInfo = new System.Diagnostics.ProcessStartInfo(flacPath, "--silent -d " + "\"" + flacTempName + "\" --output-name=\"" + wavTempName + "\""); flacProcessStartInfo.UseShellExecute = false; flacProcessStartInfo.WorkingDirectory = path; flacProcessStartInfo.ErrorDialog = false; flacProcessStartInfo.CreateNoWindow = true; flacProcessStartInfo.RedirectStandardOutput = true; flacProcessStartInfo.RedirectStandardError = true; try { Process flacProcess = System.Diagnostics.Process.Start(flacProcessStartInfo); flacProcess.WaitForExit(); System.IO.StreamReader flacStdoutReader = flacProcess.StandardOutput; string flacStdout = flacStdoutReader.ReadToEnd(); flacStdoutReader.Close(); Console.WriteLine(flacStdout); System.IO.StreamReader flacStderrReader = flacProcess.StandardError; string flacStderr = flacStderrReader.ReadToEnd(); flacStderrReader.Close(); Console.WriteLine(flacStderr); } catch (Exception ex) { Console.WriteLine(ex.Message); } try { System.IO.File.Delete(flacTempName); } catch (Exception ex) { Console.WriteLine(ex.Message); } string lameArgs = "-V 0 --vbr-new --silent --add-id3v2 --ignore-tag-errors --tc \"LAME 3.99r V0\""; if (album != "" && album != null) { Console.WriteLine(album); lameArgs += " --tl \"" + album + "\""; } if (artist != "" && artist != null) { Console.WriteLine(artist); lameArgs += " --ta \"" + artist + "\""; } if (date != "" && date != null) { Console.WriteLine(date); lameArgs += " --ty \"" + date + "\""; } if (genre != "" && genre != null) { Console.WriteLine(genre); lameArgs += " --tg \"" + genre + "\""; } if (title != "" && title != null) { Console.WriteLine(title); lameArgs += " --tt \"" + title + "\""; } if (trackNumber == "" || trackNumber == null) { trackNumber = count.ToString(); } if (trackNumber != "" && trackNumber != null) { if (trackNumber.Length == 1) { trackNumber = "0" + trackNumber; } string numberOfTracks = files.Count.ToString(); if (numberOfTracks.Length == 1) { numberOfTracks = "0" + numberOfTracks; } Console.WriteLine(trackNumber); lameArgs += " --tn \"" + trackNumber + "/" + numberOfTracks + "\""; } lameArgs += " \"" + wavTempName + "\""; string destinationName = path; if (destinationName[destinationName.Length - 1] != '\\') { destinationName += "\\"; } if ((trackNumber != "") && (title != "")) { destinationName += trackNumber + " " + title + ".mp3"; } else { destinationName += file.Name + ".mp3"; } int fileNamePosition = destinationName.LastIndexOf(System.IO.Path.DirectorySeparatorChar) + 1; System.Text.StringBuilder destinationNameBuilder = new System.Text.StringBuilder(); destinationNameBuilder.Append(destinationName.Substring(0, fileNamePosition)); for (int i = fileNamePosition; i < destinationName.Length; i++) { char fileNameChar = destinationName[i]; if (fileNameChar.Equals('~') || fileNameChar.Equals('〜')) { fileNameChar = '_'; } else { foreach (char c in System.IO.Path.GetInvalidFileNameChars()) { if (fileNameChar.Equals(c)) { fileNameChar = '_'; break; } } } destinationNameBuilder.Append(fileNameChar); } destinationName = destinationNameBuilder.ToString(); lameArgs += " \"" + destinationName + "\""; System.Diagnostics.ProcessStartInfo lameProcessStartInfo = new System.Diagnostics.ProcessStartInfo(lamePath, lameArgs); lameProcessStartInfo.UseShellExecute = false; lameProcessStartInfo.WorkingDirectory = path; lameProcessStartInfo.ErrorDialog = false; lameProcessStartInfo.CreateNoWindow = true; lameProcessStartInfo.RedirectStandardOutput = true; try { Process lameProcess = System.Diagnostics.Process.Start(lameProcessStartInfo); lameProcess.WaitForExit(); System.IO.StreamReader lameOutputReader = lameProcess.StandardOutput; string lameOutput = lameOutputReader.ReadToEnd(); lameOutputReader.Close(); Console.WriteLine(lameOutput); } catch (Exception ex) { Console.WriteLine(ex.Message); } try { System.IO.File.Delete(wavTempName); } catch (Exception ex) { Console.WriteLine(ex.Message); } } }
// // PrepareSyncPMP(string sourcePath, string destinationPath, ref Queue<UpdateLocation> UpdateFiles) // Scans the PMP, removes unnecessary files and folders, and determines what new files need to be copied // public double PrepareSyncPMP(string sourcePath, string destinationPath, ref Queue<UpdateLocation> UpdateFiles) { double size = 0; //size of all files in this directory that will need to be copied bool dirExisted = DirExisted(destinationPath); if (!Directory.Exists(destinationPath)) return size; //the directory could not be accessed //get the source files string[] sourceFiles = null; try { sourceFiles = Directory.GetFiles(sourcePath); } catch (Exception ex) { Console.WriteLine(ex); return size; } foreach (string sourceFile in sourceFiles) { string correctFile = sourceFile; if (Path.GetExtension(sourceFile) == ".flac") { try { Luminescence.Xiph.FlacTagger flacTag = new FlacTagger(correctFile); //get the flac's tag if (flacTag.BitsPerSample > 16 || flacTag.SampleRate > 48000) { if (File.Exists(DownscaledLibrary + sourceFile.Substring(MusicLibrary.Length))) correctFile = DownscaledLibrary + sourceFile.Substring(MusicLibrary.Length); //redirect to downscaled file else if (PreventSynchingUpscaled) continue; } } catch (Exception ex) { Console.WriteLine(ex); } } FileInfo sourceInfo = new FileInfo(correctFile); string destinationFile = Path.Combine(destinationPath, sourceInfo.Name); if (dirExisted && File.Exists(destinationFile)) { FileInfo destinationInfo = new FileInfo(destinationFile); if (sourceInfo.LastWriteTime > destinationInfo.LastWriteTime) { //file is newer, so add it to the queue of files that need to be copied UpdateLocation update = new UpdateLocation(); update.SourceFile = correctFile; update.DestinationFile = Path.Combine(destinationPath, sourceInfo.Name); UpdateFiles.Enqueue(update); FileInfo info = new FileInfo(correctFile); size += info.Length; //get the file's size } } else { //add it to the queue of files that need to be copied UpdateLocation update = new UpdateLocation(); update.SourceFile = correctFile; update.DestinationFile = Path.Combine(destinationPath, sourceInfo.Name); UpdateFiles.Enqueue(update); FileInfo info = new FileInfo(correctFile); size += info.Length; //get the file's size } } DeleteOldDestinationFiles(sourceFiles, destinationPath); //now process the directories if exist string[] dirs = null; try { dirs = Directory.GetDirectories(sourcePath); } catch (Exception ex) { Console.WriteLine(ex); return size; } DeleteOldDestinationDirectories(dirs, destinationPath); foreach (string dir in dirs) { if (dir == DownscaledLibrary.Substring(0, DownscaledLibrary.Length - 1)) continue; //skip downscaled folder if (EnableChiptunes && dir == ChiptunesLibrary.Substring(0, ChiptunesLibrary.Length - 1)) continue; //skip chiptunes folder DirectoryInfo dirInfo = new DirectoryInfo(dir); //recursive do the directories size += PrepareSyncPMP(dir, Path.Combine(destinationPath, dirInfo.Name), ref UpdateFiles); } return size; }
// // GetDownscaledDirectorySize(string root, double size, ref long flac) // Calculates a directory size for the downscaled library // private double GetDownscaledDirectorySize(string root, double size, ref long flac) { if (!Directory.Exists(root)) { if (AutoHandle && Directory.Exists(MusicLibrary)) Directory.CreateDirectory(root); //create the directory if it doesn't exist return size; } string[] files = null; string[] folders = null; try { files = Directory.GetFiles(root, "*.*"); //get array of all file names folders = Directory.GetDirectories(root); //get array of all folder names for this directory } catch (Exception ex) { Console.WriteLine(ex); return size; } foreach (string name in files) { FileInfo info = new FileInfo(name); //read in the file String ext = Path.GetExtension(name).ToLowerInvariant(); //get the file's extension //increment count based upon file type and extension type if (ext == ".flac") { Boolean valid = false; Boolean scanned = false; scanned = checkedFiles.TryGetValue(name, out valid); if (scanned && valid) { size += info.Length; //add to the size flac++; } else if (scanned && !valid) { if (RemoveImproper) { try { File.SetAttributes(name, FileAttributes.Normal); File.Delete(name); //downscaled flac not necessary } catch (Exception ex) { Console.WriteLine(ex); } } else { if (ShowFiles) this.Invoke(new MethodInvoker(() => lbNotDownscaled.Items.Add(name))); //show the file in the list size += info.Length; //add to the size flac++; } } else { string defaultFile = MusicLibrary + name.Substring(DownscaledLibrary.Length); valid = false; scanned = false; scanned = checkedFiles.TryGetValue(name, out valid); checkedFiles.TryGetValue(defaultFile, out valid); if (scanned && !valid) { size += info.Length; //add to the size flac++; } else if (scanned && valid) { if (RemoveUnnecessary) { try { File.SetAttributes(name, FileAttributes.Normal); File.Delete(name); //file is unnecessary } catch (Exception ex) { Console.WriteLine(ex); } } } else { try { Luminescence.Xiph.FlacTagger flacTag = new FlacTagger(name); //get the flac's tag if (!File.Exists(defaultFile)) { if (RemoveUnnecessary) { try { File.SetAttributes(name, FileAttributes.Normal); File.Delete(name); //flac's upscaled file does not exist and is unnecessary } catch (Exception ex) { Console.WriteLine(ex); } } else { size += info.Length; //add to the size flac++; } } else if (flacTag.BitsPerSample > 16 || flacTag.SampleRate > 48000) { if (RemoveImproper) { try { File.SetAttributes(name, FileAttributes.Normal); File.Delete(name); //downscaled flac not necessary } catch (Exception ex) { Console.WriteLine(ex); } } else { if (ShowFiles) this.Invoke(new MethodInvoker(() => lbNotDownscaled.Items.Add(name))); //show the file in the list size += info.Length; //add to the size flac++; } } else { try { flacTag = new FlacTagger(defaultFile); if (flacTag.BitsPerSample > 16 || flacTag.SampleRate > 48000) { size += info.Length; //add to the size flac++; //flac is ok to use } else { if (RemoveUnnecessary) { try { File.SetAttributes(name, FileAttributes.Normal); File.Delete(name); //flac did not need downscaling and is unnecessary } catch (Exception ex) { Console.WriteLine(ex); } } else { size += info.Length; //add to the size flac++; } } } catch (Exception ex) { Console.WriteLine(ex); try { if (RemoveImproper) { File.SetAttributes(name, FileAttributes.Normal); File.Delete(name); //flactag could not be read, so assume the file is invalid } } catch (Exception exDelete) { Console.WriteLine(exDelete); } } } flacTag = null; } catch (Exception ex) { Console.WriteLine(ex); } } } } else if (RemoveUnsupported) { try { File.SetAttributes(name, FileAttributes.Normal); File.Delete(name); //remove unsupported files } catch (Exception ex) { Console.WriteLine(ex); } } } foreach (string name in folders) { size = GetDownscaledDirectorySize(name, size, ref flac); //recurse through the folders } if (RemoveEmpty && !Directory.EnumerateFileSystemEntries(root).Any() && Path.GetFullPath(root) != DownscaledLibrary) { try { Directory.Delete(root); //delete empty folders } catch (Exception ex) { Console.WriteLine(ex); } return size; } return size; }
// // GetDirectorySize(string root, double size, ref long flac, ref long mp3, ref long wma, ref long m4a, ref long ogg, ref long wav, ref long xm, ref long mod, ref long nsf) // Calculates a directory size and counts the number of unique file types // private double GetDirectorySize(string root, double size, ref long flac, ref long mp3, ref long wma, ref long m4a, ref long ogg, ref long wav, ref long xm, ref long mod, ref long nsf) { if (!Directory.Exists(root)) return size; //path is invalid string[] files = null; string[] folders = null; try { files = Directory.GetFiles(root, "*.*"); //get array of all file names folders = Directory.GetDirectories(root); //get array of all folder names for this directory } catch (Exception ex) { Console.WriteLine(ex); return size; } foreach (string name in files) { FileInfo info = new FileInfo(name); //read in the file String ext = Path.GetExtension(name).ToLowerInvariant(); //get the file's extension size += info.Length; //get the length //increment count based upon file type and extension type if (ext == ".flac") { flac++; try { Luminescence.Xiph.FlacTagger flacTag = new FlacTagger(name); //get the flac's tag if (flacTag.BitsPerSample > 16 || flacTag.SampleRate > 48000) { checkedFiles.Add(name, false); //mark that it has been checked and is proper string downscaledFile = DownscaledLibrary + name.Substring(MusicLibrary.Length); if (File.Exists(downscaledFile)) { try { flacTag = new FlacTagger(downscaledFile); if (flacTag.BitsPerSample > 16 || flacTag.SampleRate > 48000) { this.Invoke(new MethodInvoker(() => lbNotDownscaled.Items.Add(name))); //if it does not meet the minimum requirements, it needs to be downscaled checkedFiles.Add(downscaledFile, false); //mark that it has been checked and is not proper } else checkedFiles.Add(downscaledFile, true); //mark that it has been checked and is proper } catch (Exception ex) { Console.WriteLine(ex); this.Invoke(new MethodInvoker(() => lbNotDownscaled.Items.Add(name))); //something is wrong with the downscaled file checkedFiles.Add(downscaledFile, false); //mark that it has been checked and is not proper } } else this.Invoke(new MethodInvoker(() => lbNotDownscaled.Items.Add(name))); //no downscaled file exists } else checkedFiles.Add(name, true); //mark that it has been checked and is not proper flacTag = null; //make sure it is not accessed again } catch (Exception ex) { Console.WriteLine(ex); } } else if (ext == ".mp3") mp3++; else if (ext == ".wma") wma++; else if (ext == ".m4a") m4a++; else if (ext == ".ogg") ogg++; else if (ext == ".wav") wav++; else if (ext == ".xm") xm++; else if (ext == ".mod") mod++; else if (ext == ".nsf") nsf++; } foreach (string name in folders) { if (Path.GetFullPath(name) == DownscaledLibrary.Substring(0, DownscaledLibrary.Length - 1)) continue; //don't scan through the downscaled files //hide all .mediaartlocal folders else if (HideMediaArtLocal && Path.GetFileName(name) == ".mediaartlocal") { try { File.SetAttributes(Path.GetFullPath(name), FileAttributes.Hidden | FileAttributes.System); } catch (Exception ex) { Console.WriteLine(ex); return size; } } size = GetDirectorySize(name, size, ref flac, ref mp3, ref wma, ref m4a, ref ogg, ref wav, ref xm, ref mod, ref nsf); //recurse through the folders } return size; }
public static void UpdateId3(Music objEntity) { string path = string.Empty; if (string.IsNullOrWhiteSpace(objEntity.FilePath) == false && string.IsNullOrWhiteSpace(objEntity.FileName) == false) { path = Path.Combine(objEntity.FilePath, objEntity.FileName); } else if (string.IsNullOrWhiteSpace(objEntity.FilePath) == true && string.IsNullOrWhiteSpace(objEntity.FileName) == false) { path = objEntity.FileName; } else if (string.IsNullOrWhiteSpace(objEntity.FilePath) == false && string.IsNullOrWhiteSpace(objEntity.FileName) == true) { path = objEntity.FilePath; } if (string.IsNullOrWhiteSpace(path) == false) { if (Directory.Exists(path)) { int index; byte[] cover = RessourcesServices.GetDefaultCover(objEntity, out index); DirectoryInfo folder = new DirectoryInfo(path); FileInfo[] files = folder.GetFiles("*.mp3", SearchOption.TopDirectoryOnly); files = files.Concat(folder.GetFiles("*.flc", SearchOption.TopDirectoryOnly)).ToArray(); files = files.Concat(folder.GetFiles("*.flac", SearchOption.TopDirectoryOnly)).ToArray(); if (files.Any()) { foreach (FileInfo file in files) { switch (file.Extension) { case ".mp3": IID3v2 objMp3Tag = ID3v2Helper.CreateID3v2(file.FullName); if (objMp3Tag != null) { objMp3Tag.Album = objEntity.Album; objMp3Tag.Artist = objEntity.Artists.First().FulleName; objMp3Tag.Accompaniment = objEntity.Artists.First().FulleName; Genre genre = objEntity.Genres.FirstOrDefault(); if (genre != null) { objMp3Tag.Genre = genre.DisplayName; } if (cover != null) { while (objMp3Tag.PictureList.Any()) { objMp3Tag.PictureList.Remove(objMp3Tag.PictureList[0]); } IAttachedPicture picture = objMp3Tag.PictureList.AddNew(); if (picture != null) { picture.PictureData = cover; picture.PictureType = PictureType.CoverFront; // optional } } objMp3Tag.Save(file.FullName); } break; case ".flac": case ".flc": FlacTagger flacTaggerTag = new FlacTagger(file.FullName); flacTaggerTag.Album = objEntity.Album; flacTaggerTag.Artist = objEntity.Artists.First().FulleName; flacTaggerTag.Performer = objEntity.Artists.First().FulleName; Genre musicGenre = objEntity.Genres.FirstOrDefault(); if (musicGenre != null) { flacTaggerTag.Genre = musicGenre.DisplayName; } if (cover != null) { while (flacTaggerTag.Arts.Any()) { flacTaggerTag.RemoveArt(flacTaggerTag.Arts[0]); } ID3PictureFrame picture = new ID3PictureFrame(cover, ID3PictureType.FrontCover); flacTaggerTag.AddArt(picture); } flacTaggerTag.SaveMetadata(); break; } } } } } }