/// <summary> /// Generates the audio book. /// </summary> /// <param name="dictionary">The dictionary.</param> /// <param name="audiobook">The target audiobook file.</param> /// <param name="options">The options.</param> /// <param name="worker">The worker.</param> /// <param name="codecs">The codecs.</param> /// <remarks>Documented by Dev02, 2008-03-10</remarks> public static void GenerateAudioBook(IDictionary dictionary, FileInfo audiobook, AudioBookOptions options, Codecs codecs) { if (workerthread != null && workerthread.IsAlive) { AddLog("Error: Another operation is still active."); return; } workerthread = new Thread(delegate() { try { Dictionary <string, Codec> encodeCodecs = codecs.encodeCodecs; Dictionary <string, Codec> decodeCodecs = codecs.decodeCodecs; if (audiobook.Extension.ToLowerInvariant() != Resources.AUDIO_WAVE_EXTENSION.ToLowerInvariant() && !encodeCodecs.ContainsKey(audiobook.Extension.ToLowerInvariant())) { AddLog(string.Format("Specified extension ({0}) is not available => Check encoder settings", audiobook.Extension.ToLowerInvariant())); return; } List <MediaFieldFile> sourcefiles = new List <MediaFieldFile>(); //source files from dictionary Environment.CurrentDirectory = new FileInfo(dictionary.Connection).Directory.FullName; //fetch source audio files AddLog("Fetching source audio files"); int count = dictionary.Cards.Cards.Count; int index = 0; foreach (ICard card in dictionary.Cards.Cards) { sourcefiles.AddRange(GetCardMediaFiles(card, options.MediaFields)); ReportProgress(index++, count); } //search and generate a new temp folder DirectoryInfo tempfolder; int tempfolderindex = 0; do { tempfolder = new DirectoryInfo(Path.Combine(Path.GetTempPath(), Settings.Default.TempFolderPath + tempfolderindex.ToString())); tempfolderindex++; } while (tempfolder.Exists); tempfolder.Create(); try { //convert all source files to wave where necessary AddLog("Converting source files"); bool foundfile = false; count = sourcefiles.Count; index = 0; for (int i = 0; i < sourcefiles.Count; i++) { if (sourcefiles[i].ContainsFile && decodeCodecs.ContainsKey(sourcefiles[i].Extension)) { //decode file string filename = sourcefiles[i].file.Name; sourcefiles[i].file = decodeCodecs[sourcefiles[i].Extension].Decode(sourcefiles[i].file, tempfolder, Settings.Default.ShowDecodingWindow, Settings.Default.MimimizeWindows); if (sourcefiles[i].ContainsFile) { foundfile = true; } else { AddLog(string.Format("Decoding ({0}) did not produce a file => Check decoder settings", filename)); } } else if (sourcefiles[i].ContainsFile && sourcefiles[i].Extension == Resources.AUDIO_WAVE_EXTENSION.ToLowerInvariant()) { foundfile = true; } else if (sourcefiles[i].ContainsFile) { AddLog(string.Format("Extension {0} not supported ({1}) => Check decoder settings", sourcefiles[i].Extension, sourcefiles[i].file.Name)); } ReportProgress(index++, count); } if (!foundfile) { AddLog("No supported audio files found in the selected fields of the learning module"); ReportProgress(0, 0); //disable progress reporting } else { //concatenate all wave files AddLog("Joining audio files"); FileInfo audiobookwave = new FileInfo(Path.Combine(tempfolder.FullName, Resources.AUDIOBOOK_DEFAULTNAME + Resources.AUDIO_WAVE_EXTENSION)); ABWaveCat wavecat = new ABWaveCat(); wavecat.Concatenate(sourcefiles, audiobookwave, options.Stereo); ReportProgress(0, 0); //disable progress reporting bool changeToWaveExtension = true; //fix for [MLA-1272] error message for file path without extension if (audiobook.Extension.ToLowerInvariant() != Resources.AUDIO_WAVE_EXTENSION.ToLowerInvariant()) { if (encodeCodecs.ContainsKey(audiobook.Extension.ToLowerInvariant())) { //convert audiobook to specified format AddLog("Converting audiobook"); FileInfo encodedfile = encodeCodecs[audiobook.Extension.ToLowerInvariant()].Encode(audiobookwave, tempfolder, Settings.Default.ShowEncodingWindow, Settings.Default.MimimizeWindows); if (encodedfile != null) { try { if (audiobook.Exists) { audiobook.Delete(); } encodedfile.MoveTo(audiobook.FullName); changeToWaveExtension = false; } catch (Exception e) { AddLog("Could not replace audio file: " + e.Message); return; } } else { AddLog(string.Format("Encoding ({0}) did not produce a file => Check encoder settings", audiobook.Name)); } } } if (changeToWaveExtension) //change file to wave extension and force wave generation { audiobook = new FileInfo(Path.ChangeExtension(audiobook.FullName, Resources.AUDIO_WAVE_EXTENSION)); } if (audiobook.Extension.ToLowerInvariant() == Resources.AUDIO_WAVE_EXTENSION.ToLowerInvariant()) { try { if (audiobook.Exists) { audiobook.Delete(); } audiobookwave.MoveTo(audiobook.FullName); } catch (Exception e) { AddLog("Could not replace audio file: " + e.Message); return; } } AddLog("Finished: " + audiobook.FullName); } } finally { //try to delete the temp directory (try multiple times in case it is still locked) Thread cleanthread = new Thread(delegate() { int tries = 0; while (tries++ < 10) { System.Threading.Thread.Sleep(1000); try { tempfolder.Delete(true); TempFiles.ForEach(f => f.Delete()); break; } catch { } } }); cleanthread.IsBackground = true; cleanthread.Start(); } } catch (Exception exp) { ReportProgress(0, 0); //disable progressbar if (exp is ThreadAbortException) { AddLog("Operation cancelled"); } else { AddLog("GenerateAudioBook Thread Exception: " + exp.ToString()); } } finally { //fire the working thread finished event in every case OnWorkingThreadFinished(EventArgs.Empty); } }); workerthread.IsBackground = true; workerthread.Start(); return; }
/// <summary> /// Generates the audio book. /// </summary> /// <param name="dictionary">The dictionary.</param> /// <param name="audiobook">The target audiobook file.</param> /// <param name="options">The options.</param> /// <param name="worker">The worker.</param> /// <param name="codecs">The codecs.</param> /// <remarks>Documented by Dev02, 2008-03-10</remarks> public static void GenerateAudioBook(IDictionary dictionary, FileInfo audiobook, AudioBookOptions options, Codecs codecs) { if (workerthread != null && workerthread.IsAlive) { AddLog("Error: Another operation is still active."); return; } workerthread = new Thread(delegate() { try { Dictionary<string, Codec> encodeCodecs = codecs.encodeCodecs; Dictionary<string, Codec> decodeCodecs = codecs.decodeCodecs; if (audiobook.Extension.ToLowerInvariant() != Resources.AUDIO_WAVE_EXTENSION.ToLowerInvariant() && !encodeCodecs.ContainsKey(audiobook.Extension.ToLowerInvariant())) { AddLog(string.Format("Specified extension ({0}) is not available => Check encoder settings", audiobook.Extension.ToLowerInvariant())); return; } List<MediaFieldFile> sourcefiles = new List<MediaFieldFile>(); //source files from dictionary Environment.CurrentDirectory = new FileInfo(dictionary.Connection).Directory.FullName; //fetch source audio files AddLog("Fetching source audio files"); int count = dictionary.Cards.Cards.Count; int index = 0; foreach (ICard card in dictionary.Cards.Cards) { sourcefiles.AddRange(GetCardMediaFiles(card, options.MediaFields)); ReportProgress(index++, count); } //search and generate a new temp folder DirectoryInfo tempfolder; int tempfolderindex = 0; do { tempfolder = new DirectoryInfo(Path.Combine(Path.GetTempPath(), Settings.Default.TempFolderPath + tempfolderindex.ToString())); tempfolderindex++; } while (tempfolder.Exists); tempfolder.Create(); try { //convert all source files to wave where necessary AddLog("Converting source files"); bool foundfile = false; count = sourcefiles.Count; index = 0; for (int i = 0; i < sourcefiles.Count; i++) { if (sourcefiles[i].ContainsFile && decodeCodecs.ContainsKey(sourcefiles[i].Extension)) { //decode file string filename = sourcefiles[i].file.Name; sourcefiles[i].file = decodeCodecs[sourcefiles[i].Extension].Decode(sourcefiles[i].file, tempfolder, Settings.Default.ShowDecodingWindow, Settings.Default.MimimizeWindows); if (sourcefiles[i].ContainsFile) foundfile = true; else AddLog(string.Format("Decoding ({0}) did not produce a file => Check decoder settings", filename)); } else if (sourcefiles[i].ContainsFile && sourcefiles[i].Extension == Resources.AUDIO_WAVE_EXTENSION.ToLowerInvariant()) foundfile = true; else if (sourcefiles[i].ContainsFile) AddLog(string.Format("Extension {0} not supported ({1}) => Check decoder settings", sourcefiles[i].Extension, sourcefiles[i].file.Name)); ReportProgress(index++, count); } if (!foundfile) { AddLog("No supported audio files found in the selected fields of the learning module"); ReportProgress(0, 0); //disable progress reporting } else { //concatenate all wave files AddLog("Joining audio files"); FileInfo audiobookwave = new FileInfo(Path.Combine(tempfolder.FullName, Resources.AUDIOBOOK_DEFAULTNAME + Resources.AUDIO_WAVE_EXTENSION)); ABWaveCat wavecat = new ABWaveCat(); wavecat.Concatenate(sourcefiles, audiobookwave, options.Stereo); ReportProgress(0, 0); //disable progress reporting bool changeToWaveExtension = true; //fix for [MLA-1272] error message for file path without extension if (audiobook.Extension.ToLowerInvariant() != Resources.AUDIO_WAVE_EXTENSION.ToLowerInvariant()) { if (encodeCodecs.ContainsKey(audiobook.Extension.ToLowerInvariant())) { //convert audiobook to specified format AddLog("Converting audiobook"); FileInfo encodedfile = encodeCodecs[audiobook.Extension.ToLowerInvariant()].Encode(audiobookwave, tempfolder, Settings.Default.ShowEncodingWindow, Settings.Default.MimimizeWindows); if (encodedfile != null) { try { if (audiobook.Exists) audiobook.Delete(); encodedfile.MoveTo(audiobook.FullName); changeToWaveExtension = false; } catch (Exception e) { AddLog("Could not replace audio file: " + e.Message); return; } } else { AddLog(string.Format("Encoding ({0}) did not produce a file => Check encoder settings", audiobook.Name)); } } } if (changeToWaveExtension) //change file to wave extension and force wave generation audiobook = new FileInfo(Path.ChangeExtension(audiobook.FullName, Resources.AUDIO_WAVE_EXTENSION)); if (audiobook.Extension.ToLowerInvariant() == Resources.AUDIO_WAVE_EXTENSION.ToLowerInvariant()) { try { if (audiobook.Exists) audiobook.Delete(); audiobookwave.MoveTo(audiobook.FullName); } catch (Exception e) { AddLog("Could not replace audio file: " + e.Message); return; } } AddLog("Finished: " + audiobook.FullName); } } finally { //try to delete the temp directory (try multiple times in case it is still locked) Thread cleanthread = new Thread(delegate() { int tries = 0; while (tries++ < 10) { System.Threading.Thread.Sleep(1000); try { tempfolder.Delete(true); TempFiles.ForEach(f => f.Delete()); break; } catch { } } }); cleanthread.IsBackground = true; cleanthread.Start(); } } catch (Exception exp) { ReportProgress(0, 0); //disable progressbar if (exp is ThreadAbortException) { AddLog("Operation cancelled"); } else { AddLog("GenerateAudioBook Thread Exception: " + exp.ToString()); } } finally { //fire the working thread finished event in every case OnWorkingThreadFinished(EventArgs.Empty); } }); workerthread.IsBackground = true; workerthread.Start(); return; }
/// <summary> /// Handles the Click event of the buttonStart control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> /// <remarks>Documented by Dev02, 2008-03-17</remarks> private void buttonStart_Click(object sender, EventArgs e) { if (BusinessLayer.WorkingThreadActive) { BusinessLayer.AbortWorkingThread(); return; } textBoxLog.Clear(); tracelistener.LogMessages.Clear(); //check if input file exists if (!File.Exists(textBoxLearningModule.Text)) { BusinessLayer.AddLog("The specified learning module file cannot be found"); return; } //check if any audio fields are selected if (listViewPlaybackSequence.Items.Count == 0) { BusinessLayer.AddLog("Please select at least one field for the playback sequence"); return; } IDictionary dictionary = null; try { AudioBookOptions options = new AudioBookOptions(); //add mono/stereo selection to options options.Stereo = radioButtonStereo.Checked; //add selected fields to the options foreach (ListViewItem lvi in listViewPlaybackSequence.Items) { MediaField mediafield = lvi.Tag as MediaField; if (mediafield != null) options.MediaFields.Add(mediafield); } //check for valid file paths FileInfo dictionaryfile = null, audiobook = null; try { dictionaryfile = new FileInfo(textBoxLearningModule.Text); audiobook = new FileInfo(textBoxAudiobook.Text); if (string.IsNullOrEmpty(audiobook.Extension)) { BusinessLayer.AddLog("Please enter a valid extension for the target audiobook file"); return; } } catch { BusinessLayer.AddLog("The specified file paths are not valid. Please check your input"); return; } //save file paths to settings as recent files Settings.Default.RecentLearningModule = dictionaryfile.FullName; Settings.Default.RecentAudioBook = audiobook.FullName; Settings.Default.Save(); //open learning module and start audio book generation try { ConnectionStringStruct css = new ConnectionStringStruct(DatabaseType.MsSqlCe, dictionaryfile.FullName); MLifter.DAL.Interfaces.IUser user = UserFactory.Create((GetLoginInformation)MLifter.Controls.LoginForm.OpenLoginForm, css, (DataAccessErrorDelegate)delegate { return; }, this); css.LmId = User.GetIdOfLearningModule(dictionaryfile.FullName, user); user.ConnectionString = css; dictionary = user.Open(); } catch (System.IO.IOException) { BusinessLayer.AddLog("The Learning Module file could not be accessed. Please make sure that it is not open within another program (e.g. MemoryLifter)"); return; } catch (System.Xml.XmlException) { BusinessLayer.AddLog("The Learning Module file does not seem to be in a valid format"); return; } catch (ProtectedLearningModuleException) { BusinessLayer.AddLog("The Learning Module could not be opened: It is content protected"); return; } catch (Exception exp) { BusinessLayer.AddLog("The Learning Module file could not be opened:" + Environment.NewLine + exp.Message); return; } buttonStart.Text = "Cancel"; BusinessLayer.GenerateAudioBook(dictionary, audiobook, options, codecs); } catch (Exception exp) { BusinessLayer.AddLog("Audio book generation exception happened: " + Environment.NewLine + exp.ToString()); return; } finally { if (dictionary != null) dictionary.Dispose(); } }
/// <summary> /// Handles the Click event of the buttonStart control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> /// <remarks>Documented by Dev02, 2008-03-17</remarks> private void buttonStart_Click(object sender, EventArgs e) { if (BusinessLayer.WorkingThreadActive) { BusinessLayer.AbortWorkingThread(); return; } textBoxLog.Clear(); tracelistener.LogMessages.Clear(); //check if input file exists if (!File.Exists(textBoxLearningModule.Text)) { BusinessLayer.AddLog("The specified learning module file cannot be found"); return; } //check if any audio fields are selected if (listViewPlaybackSequence.Items.Count == 0) { BusinessLayer.AddLog("Please select at least one field for the playback sequence"); return; } IDictionary dictionary = null; try { AudioBookOptions options = new AudioBookOptions(); //add mono/stereo selection to options options.Stereo = radioButtonStereo.Checked; //add selected fields to the options foreach (ListViewItem lvi in listViewPlaybackSequence.Items) { MediaField mediafield = lvi.Tag as MediaField; if (mediafield != null) { options.MediaFields.Add(mediafield); } } //check for valid file paths FileInfo dictionaryfile = null, audiobook = null; try { dictionaryfile = new FileInfo(textBoxLearningModule.Text); audiobook = new FileInfo(textBoxAudiobook.Text); if (string.IsNullOrEmpty(audiobook.Extension)) { BusinessLayer.AddLog("Please enter a valid extension for the target audiobook file"); return; } } catch { BusinessLayer.AddLog("The specified file paths are not valid. Please check your input"); return; } //save file paths to settings as recent files Settings.Default.RecentLearningModule = dictionaryfile.FullName; Settings.Default.RecentAudioBook = audiobook.FullName; Settings.Default.Save(); //open learning module and start audio book generation try { ConnectionStringStruct css = new ConnectionStringStruct(DatabaseType.MsSqlCe, dictionaryfile.FullName); MLifter.DAL.Interfaces.IUser user = UserFactory.Create((GetLoginInformation)MLifter.Controls.LoginForm.OpenLoginForm, css, (DataAccessErrorDelegate) delegate { return; }, this); css.LmId = User.GetIdOfLearningModule(dictionaryfile.FullName, user); user.ConnectionString = css; dictionary = user.Open(); } catch (System.IO.IOException) { BusinessLayer.AddLog("The Learning Module file could not be accessed. Please make sure that it is not open within another program (e.g. MemoryLifter)"); return; } catch (System.Xml.XmlException) { BusinessLayer.AddLog("The Learning Module file does not seem to be in a valid format"); return; } catch (ProtectedLearningModuleException) { BusinessLayer.AddLog("The Learning Module could not be opened: It is content protected"); return; } catch (Exception exp) { BusinessLayer.AddLog("The Learning Module file could not be opened:" + Environment.NewLine + exp.Message); return; } buttonStart.Text = "Cancel"; BusinessLayer.GenerateAudioBook(dictionary, audiobook, options, codecs); } catch (Exception exp) { BusinessLayer.AddLog("Audio book generation exception happened: " + Environment.NewLine + exp.ToString()); return; } finally { if (dictionary != null) { dictionary.Dispose(); } } }