Пример #1
0
        /// <summary>
        /// Invokes the name parser to rename the specified file according to naming conventions, and closes the window if successful.
        /// </summary>
        private void renameCurrentFile()
        {
            try
            {
                NameParser parser = new NameParser();
                parser.Address  = Path.GetDirectoryName(file.FullName);
                parser.Ext      = Path.GetExtension(file.FullName);
                parser.Speaker  = ConvertDisplayVoiceType((string)speakerComboBox.SelectedItem);
                parser.Category = categoryComboBox.Text;
                parser.Word     = WordComboBox.Text;
                parser.Label    = labelTextBox.Text;

                File.Move(file.FullName, parser.SingleFile);

                RenamedFile  = new FileInfo(parser.SingleFile);
                DialogResult = DialogResult.OK;
                Close();
            }
            catch (Exception exp)
            {
                if (exp.GetType() == typeof(FileNotFoundException))
                {
                    MPAiMessageBoxFactory.Show(exp.Message, noSuchFileText);
                }
                else if (exp.GetType() == typeof(IOException))
                {
                    MPAiMessageBoxFactory.Show(exp.Message, alreadyExistsText);
                }
            }
        }
Пример #2
0
 /// <summary>
 /// Verifies the password in the text box is valid, prompts the user, then closes the window if successful.
 /// </summary>
 private void changePassword()
 {
     // If you want requirements for passwords, (such as 8 characters in length, etc.) implement it here.
     if ((codeBox.Text.Trim() == "") || (codeBox2.Text.Trim() == ""))
     {
         MPAiMessageBoxFactory.Show("Passwords should not be empty!",
                                    "Oops", MPAiMessageBoxButtons.OK);
     }
     else if (codeBox.Text != codeBox2.Text)
     {
         MPAiMessageBoxFactory.Show("Passwords do not match!",
                                    "Oops", MPAiMessageBoxButtons.OK);
     }
     else if (codeBox.Text.Equals(currentUser.getCode()))
     {
         MPAiMessageBoxFactory.Show("That is already your password!",
                                    "Oops", MPAiMessageBoxButtons.OK);
     }
     else
     {
         UserManagement.ChangeCurrentUserCode(codeBox.Text);
         UserManagement.WriteSettings();
         MPAiMessageBoxFactory.Show("Password changed! ",
                                    "Done", MPAiMessageBoxButtons.OK);
         Close();
     }
 }
Пример #3
0
 /// <summary>
 /// Opens a file picker, then for each file picked by the user, prompts them to rename the file, and places it in the recording list.
 /// </summary>
 private void add()
 {
     try
     {
         if (openFileDialog.ShowDialog() == DialogResult.OK)
         {
             foreach (string f in openFileDialog.FileNames)
             {
                 if (f.ToCharArray().Any(c => c > 127))
                 {
                     // Then the file name contains a unicode character
                     MPAiMessageBoxFactory.Show("MPAi cannot support filenames with unicode characters. Please rename " + f + " and try again.");
                     continue;
                 }
                 else
                 {
                     string[] fArray = f.Split(Path.DirectorySeparatorChar); // Split on file separator
                     string   fShort = fArray[fArray.GetLength(0) - 1];      // Get the last index, which corresponds to just the file name
                     File.Copy(f, Path.Combine(outputFolder, fShort));       // Copy file into recordings folder.
                 }
             }
             DataBinding();
         }
     }
     catch (Exception exp)
     {
         Console.WriteLine(exp.StackTrace);
     }
 }
Пример #4
0
        /// <summary>
        /// Sets up the audio device, and the file to record into, adds listeners to the events, starts recording, and toggles the buttons.
        /// </summary>
        private void record()
        {
            try
            {
                var device = (MMDevice)AudioInputDeviceComboBox.SelectedItem;
                if (!(device == null))
                {
                    recordButton.Text          = stopText;
                    recordingProgressBar.Value = 0;

                    device.AudioEndpointVolume.Mute = false;
                    // Use wasapi by default
                    waveIn = new WasapiCapture(device);
                    waveIn.DataAvailable     += OnDataAvailable;
                    onDataAvailableSubscribed = true;
                    waveIn.RecordingStopped  += OnRecordingStopped;
                    writer = new WaveFileWriter(audioFilePath, waveIn.WaveFormat);
                    waveIn.StartRecording();
                    SetControlStates(true);
                }
                else
                {
                    recordButton.Text = recordText;
                    MPAiMessageBoxFactory.Show(noAudioDeviceText, warningText, MPAiMessageBoxButtons.OK);
                }
            }
            catch (Exception exp)
            {
#if DEBUG
                MPAiMessageBoxFactory.Show(exp.Message, warningText, MPAiMessageBoxButtons.OK);
#endif
            }
        }
Пример #5
0
        /// <summary>
        /// Gets the categories from the database.
        /// </summary>
        private void populateCategoryComboBox()
        {
            try
            {
                // Create new database context.
                using (MPAiModel DBModel = new MPAiModel())
                {
                    DBModel.Database.Initialize(false); // Added for safety; if the database has not been initialised, initialise it.

                    MPAiUser current = UserManagement.CurrentUser;

                    List <Category> view = DBModel.Category.ToList();
                    view.Reverse();
                    categoryComboBox.DataSource = new BindingSource()
                    {
                        DataSource = view
                    };
                    categoryComboBox.DisplayMember = "Name";
                }
            }
            catch (Exception exp)
            {
                MPAiMessageBoxFactory.Show(dataLinkErrorText);
                Console.WriteLine(exp);
            }
        }
Пример #6
0
        /// <summary>
        /// Gets the words from the database.
        /// </summary>
        private void populateWordComboBox()
        {
            try
            {
                // Create new database context.
                using (MPAiModel DBModel = new MPAiModel())
                {
                    DBModel.Database.Initialize(false); // Added for safety; if the database has not been initialised, initialise it.

                    MPAiUser current = UserManagement.CurrentUser;
                    UserManagement.CurrentUser.setSpeakerFromVoiceType();

                    List <Word> view = DBModel.Word.Where(x => (
                                                              x.Category.Name.Equals(((Category)categoryComboBox.SelectedItem).Name) &&
                                                              x.Recordings.Any(y => y.Speaker.SpeakerId == UserManagement.CurrentUser.Speaker.SpeakerId)
                                                              )).ToList();

                    view.Sort(new VowelComparer());
                    WordComboBox.DataSource = new BindingSource()
                    {
                        DataSource = view
                    };
                    WordComboBox.DisplayMember = "Name";
                }
            }
            catch (Exception exp)
            {
                MPAiMessageBoxFactory.Show(dataLinkErrorText);
                Console.WriteLine(exp);
            }
        }
Пример #7
0
 /// <summary>
 /// Deletes the file selected in the list box from the user's computer.
 /// </summary>
 void DeleteFile()
 {
     if (RecordingListBox.SelectedItem != null)
     {
         try
         {
             StopRecording();
             StopPlay();
             File.Delete(Path.Combine(outputFolder, (string)RecordingListBox.SelectedItem));
             if (recordingProgressBarLabel.Text.Equals((string)RecordingListBox.SelectedItem))
             {
                 recordingProgressBarLabel.Text = noCurrentFileText;
             }
             RecordingListBox.Items.Remove(RecordingListBox.SelectedItem);
             if (RecordingListBox.Items.Count > 0)
             {
                 RecordingListBox.SelectedIndex = RecordingListBox.Items.Count - 1;
             }
         }
         catch (Exception exp)
         {
             Console.WriteLine(exp);
             MPAiMessageBoxFactory.Show(couldntDeleteRecordingText);
         }
     }
     else
     {
         MPAiMessageBoxFactory.Show(recordingNotSelectedText);
     }
     // If no items remain, disable buttons relating to them.
     if (RecordingListBox.Items.Count < 1)
     {
         toggleListButtons(false);
     }
 }
Пример #8
0
        /// <summary>
        /// Plays or pauses the audio, depending on the VLC player's current state.
        /// </summary>
        private void playAudio()
        {
            using (MPAiModel DBModel = MPAiModel.InitializeDBModel())
            {
                Word    wd  = wordsList[currentRecordingIndex];
                Speaker spk = UserManagement.CurrentUser.Speaker;  // Get the speaker from user settings.
                Console.WriteLine(UserManagement.CurrentUser.Speaker.Name + " " + VoiceType.getDisplayNameFromVoiceType(UserManagement.CurrentUser.Voice));
                Recording rd = DBModel.Recording.Local.Where(x => x.WordId == wd.WordId && x.SpeakerId == spk.SpeakerId).SingleOrDefault();

                if (rd != null)
                {
                    ICollection <SingleFile> audios = rd.Audios;
                    if (audios == null || audios.Count == 0)
                    {
                        throw new Exception("No audio recording!");
                    }
                    SingleFile sf = audios.PickNext();
                    filePath = Path.Combine(sf.Address, sf.Name);

                    asyncPlay();
                    playButton.ImageIndex = 3;
                }
                else
                {
                    MPAiMessageBoxFactory.Show(invalidRecordingString);
                }
            }
        }
Пример #9
0
 /// <summary>
 /// Generates and sends an emial based on what has been input into the text fields.
 /// </summary>
 /// <param name="sender">Automatically generated by Visual Studio.</param>
 /// <param name="e">Automatically generated by Visual Studio.</param>
 private void mailSendButton_Click(object sender, EventArgs e)
 {
     try
     {
         MailSender send = new MailSender();
         if (send.ValidateEmail(customerEmailTextBox.Text))
         {
             MailMessage mail = new MailMessage();
             mail.From = new MailAddress(customerEmailTextBox.Text);
             mail.To.Add("*****@*****.**");
             mail.CC.Add("*****@*****.**");
             mail.CC.Add("*****@*****.**");
             mail.CC.Add("*****@*****.**");
             mail.Subject = mailSubjectTextBox.Text;
             mail.Body    = string.Format("{0}{1}{2}{3}This email is sent from {4}", mailContentTextBox.Text, Environment.NewLine, Environment.NewLine, Environment.NewLine, customerEmailTextBox.Text);
             send.Send(mail);
             MPAiMessageBoxFactory.Show("Mail has been sent!", "Thanks!");
             Close();
         }
         else
         {
             MPAiMessageBoxFactory.Show("Please enter a valid email address!", "Email Address Error!");
         }
     }
     catch (Exception exp)
     {
         MPAiMessageBoxFactory.Show(exp.Message, "Message Sending Error!");
     }
 }
Пример #10
0
 /// <summary>
 /// Launches the default system folder picker so the user can select a folder to upload from.
 /// </summary>
 /// <param name="sender">Automatically generated by Visual Studio.</param>
 /// <param name="e">Automatically generated by Visual Studio.</param>
 private void selectFolderButton_Click(object sender, EventArgs e)
 {
     try
     {
         if (folderBrowserDialog.ShowDialog() == DialogResult.OK)
         {
             DirectoryInfo selectedDirectory = new DirectoryInfo(folderBrowserDialog.SelectedPath);
             currentFolderTextBox.Text = selectedDirectory.FullName;
             ListBox localListBox = mediaLocalListBox;
             // Replace the values in the list box with the files in the folder that are of a valid format.
             FileInfo[] view = selectedDirectory.GetFiles().Where(
                 x => x.Extension.Equals(".wav")
                 //|| x.Extension.Equals(".mp4") // Currently, MPAi's video player cannot support multiple video files for the same sound.
                 ).ToArray();
             localListBox.DataSource = new BindingSource()
             {
                 DataSource = view
             };
             if (view.Count() < 1)
             {
                 MPAiMessageBoxFactory.Show(noValidFilesText);
             }
             localListBox.DisplayMember = "Name";     // Display the names.
         }
     }
     catch (Exception exp)
     {
         Console.WriteLine(exp);
     }
 }
Пример #11
0
        /// <summary>
        /// Authenticates the user and handles user errors.
        /// Also handles informing the user if they have entered an incorrect username or password.
        /// </summary>
        /// <returns>True if the user has logged in successfully, false otherwise.</returns>
        private bool login()
        {
            MPAiUser tUser = new MPAiUser(usernameTextBox.Text, passwordTextBox.Text);

            if (UserManagement.AuthenticateUser(ref tUser))
            {
                return(true);
            }
            else
            {
                if (UserManagement.ContainsUser(tUser))
                {
                    MPAiMessageBoxFactory.Show("Password is incorrect!",
                                               "Oops", MPAiMessageBoxButtons.OK);
                    passwordTextBox.Clear();
                    watermarkPassword(true);
                }
                else
                {
                    MPAiMessageBoxFactory.Show("User does not exist!",
                                               "Oops", MPAiMessageBoxButtons.OK);
                    usernameTextBox.Clear();
                    watermarkUsername(false);
                    passwordTextBox.Clear();
                    watermarkPassword(false);
                }
                return(false);
            }
        }
Пример #12
0
 /// <summary>
 /// Populates the text boxes on the form and creates the referenced directories if they don't already exist.
 /// </summary>
 /// <param name="tb">The text box to initialise.</param>
 /// <param name="dir">The directory to create (if needed) and fill the text box with.</param>
 private void InitializeTextBox(TextBox tb, string dir)
 {
     try
     {
         Directory.CreateDirectory(dir);
         tb.Text = dir;
     }
     catch (Exception exp)
     {
         MPAiMessageBoxFactory.Show(exp.Message);
     }
 }
Пример #13
0
 /// <summary>
 /// Loads the user's default browser to view the specified HTML file.
 /// </summary>
 /// <param name="htmlPath">The file path of the HTML file to be viewed, as a string.</param>
 public static void ShowInBrowser(string htmlPath)
 {
     try
     {
         Process browser = new Process();
         browser.StartInfo.FileName = htmlPath;
         browser.Start();
     }
     catch
     {
         MPAiMessageBoxFactory.Show(fileNotFoundText);
     }
 }
Пример #14
0
        private void deleteButtonClick(object sender, EventArgs e)
        {
            MPAiUser user = userButtonMap[(MPAiButton)sender];

            if (MPAiMessageBoxFactory.Show("Are you sure you want to delete " + user.GetCorrectlyCapitalisedName() + "'s account?", MPAiMessageBoxButtons.YesNoCancel).Equals(DialogResult.Yes))
            {
                UserManagement.RemoveUser(user);
                generatedUserTable = generateUserTable();
                this.Close();
                new AdministratorConsole().ShowDialog();
                Console.WriteLine("delete " + user.GetCorrectlyCapitalisedName());
            }
            UserManagement.WriteSettings();
        }
Пример #15
0
        /// <summary>
        /// Method called by the button to show the  plot.
        /// If there is already a  plot running, it is brought into the foreground.
        /// If not, a new process is created.
        ///
        /// requestedPlotType determines if RunPlot runs a Vowel or Formant Plot.
        /// requestedVoiceType determines if we use heratage/ modern and masculine/feminine for the plots.
        /// </summary>
        public static void RunPlot(PlotType?requestedPlotType, VoiceType requestedVoiceType)
        {
            exitRequest = false;
            plotType    = requestedPlotType;
            voiceType   = requestedVoiceType;

            var deviceEnum = new MMDeviceEnumerator();
            var devices    = deviceEnum.EnumerateAudioEndPoints(DataFlow.Capture, DeviceState.Active).ToList();

            if (devices.Count == 0)
            {
                if (plotType == PlotType.VOWEL_PLOT)
                {
                    MPAiMessageBoxFactory.Show("No recording device detected.\nVowel Plot requires a working microphone to function correctly.\nPlease plug in Microphone, or update Drivers.");
                }
                else if (plotType == PlotType.FORMANT_PLOT)
                {
                    MPAiMessageBoxFactory.Show("No recording device detected.\nFormant Plot requires a working microphone to function correctly.\nPlease plug in Microphone or update Drivers.");
                }

                MPAiSoundMainMenu menu = new MPAiSoundMainMenu();
                menu.Show();
            }
            else
            {
                foreach (var process in Process.GetProcessesByName("MPAiVowelRunner"))
                {
                    process.Kill();
                    process.WaitForExit();
                    process.Dispose();
                }
                foreach (var process in Process.GetProcessesByName("MPAiPlotRunner"))
                {
                    process.Kill();
                    process.WaitForExit();
                    process.Dispose();
                }
                if (PlotStarted(GetPlotTitle()) == 1)
                {
                    StartPlot();
                }
                else
                {
                    ShowPlot(GetPlotTitle());
                }
            }
        }
Пример #16
0
 /// <summary>
 /// Initialises all text boxes, and fills them in with values from the current system settings.
 /// </summary>
 public void InitializeContent()
 {
     try
     {
         // Audio folder.
         InitializeTextBox(this.audioFolderTextBox, DirectoryManagement.AudioFolder);
         // Recording folder.
         InitializeTextBox(this.recordingFolderTextBox, DirectoryManagement.RecordingFolder);
         // Report folder.
         InitializeTextBox(this.reportFolderTextBox, DirectoryManagement.ScoreboardReportFolder);
         // HTK folder.
         InitializeTextBox(this.HTKFolderTextBox, DirectoryManagement.HTKFolder);
     }
     catch (Exception exp)
     {
         MPAiMessageBoxFactory.Show(exp.Message);
     }
 }
Пример #17
0
 /// <summary>
 /// Initialises all text boxes, and fills them in with values from the current system settings.
 /// </summary>
 public void InitializeContent()
 {
     try
     {
         // Video folder.
         InitializeTextBox(this.videoFolderTextBox, DirectoryManagement.VideoFolder);
         // Report folder.
         InitializeTextBox(this.reportFolderTextBox, DirectoryManagement.ScoreboardReportFolder);
         // Formant folder.
         InitializeTextBox(this.formantFolderTextBox, DirectoryManagement.FormantFolder);
         // Recording folder.
         InitializeTextBox(this.recordingFolderTextBox, DirectoryManagement.RecordingFolder);
     }
     catch (Exception exp)
     {
         MPAiMessageBoxFactory.Show(exp.Message);
     }
 }
Пример #18
0
 /// <summary>
 /// Connects this program to the maintained database, and loads all relevant files.
 /// </summary>
 private void InitializeDB()
 {
     try
     {
         MPAiModel DBModel = new MPAiModel();
         DBModel.Database.Initialize(false);
         DBModel.Recording.Load();
         DBModel.Speaker.Load();
         DBModel.Category.Load();
         DBModel.Word.Load();
         DBModel.SingleFile.Load();
     }
     catch (Exception exp)
     {
         MPAiMessageBoxFactory.Show(exp.StackTrace, "Database linking error!");
         Console.WriteLine(exp.StackTrace);
     }
 }
Пример #19
0
        /// <summary>
        /// Passes the selected item to the speech recognition software.
        /// </summary>
        void analyse()
        {
            try
            {
                if (recordingProgressBarLabel.Text.ToCharArray().Any(c => c > 127))
                {
                    // Then the file name contains a unicode character
                    MPAiMessageBoxFactory.Show("MPAi cannot support filenames with unicode characters. Please rename " + recordingProgressBarLabel.Text + " and try again.");
                    return;
                }
                if (!recordingProgressBarLabel.Text.Equals(noCurrentFileText))
                {
                    string target = ((WordComboBox.SelectedItem as Word) == null) ? string.Empty : (WordComboBox.SelectedItem as Word).Name;
                    Dictionary <string, string> result = RecEngine.Recognize(Path.Combine(outputFolder, recordingProgressBarLabel.Text)).ToDictionary(x => x.Key, x => x.Value);
                    if (result.Count > 0)
                    {
                        MPAiSpeakScoreBoardItem item;
                        AnalysisScreen          analysisScreen;
                        item = new MPAiSpeakScoreBoardItem(target, result.First().Value, PronuciationAdvisor.Advise(result.First().Key, target, result.First().Value), recordingProgressBarLabel.Text);

                        if (!UserManagement.CurrentUser.SpeakScoreboard.IsRecordingAlreadyAnalysed(recordingProgressBarLabel.Text))
                        {
                            session.Content.Add(item);
                            analysisScreen = new AnalysisScreen(item.Similarity, item.Analysis);
                        }
                        else
                        {
                            analysisScreen = new AnalysisScreen(item.Similarity, item.Analysis, true);
                        }
                        analysisScreen.ShowDialog(this);
                    }
                    else
                    {
                        MPAiMessageBoxFactory.Show("There was a error while analysing this recording.\nHTK Engine did not return a match between the recording and a word.\nIf this problem persist, reinstall MPAi");
                    }
                }
            }
            catch (Exception exp)
            {
#if DEBUG
                MPAiMessageBoxFactory.Show(exp.Message, warningText, MPAiMessageBoxButtons.OK);
#endif
            }
        }
Пример #20
0
        /// <summary>
        /// Handles the functionality of the play/pause button, which differs based on the state of the player.
        /// </summary>
        /// <param name="sender">Automatically generated by Visual Studio.</param>
        /// <param name="e">Automatically generated by Visual Studio.</param>
        private void playButton_Click(object sender, EventArgs e)
        {
            try
            {
                switch (vlcControl.State)
                {
                case Vlc.DotNet.Core.Interops.Signatures.MediaStates.NothingSpecial:        // Occurs when control is finished loading. Same functionality as stopped.
                case Vlc.DotNet.Core.Interops.Signatures.MediaStates.Ended:                 // Occurs when control has finished playing a video. Same funcionaility as stopped.
                case Vlc.DotNet.Core.Interops.Signatures.MediaStates.Stopped:               // Occurs when the player has been stopped. No video is loaded in.
                {
                    playAudio();
                }
                break;

                case Vlc.DotNet.Core.Interops.Signatures.MediaStates.Playing:       // If playing, pause and update the button.
                {
                    vlcControl.Pause();
                    playButton.ImageIndex = 1;
                }
                break;

                case Vlc.DotNet.Core.Interops.Signatures.MediaStates.Paused: // If paused, play and update the button.
                {
                    vlcControl.Play();                                       // asyncPlay is not used here, as it starts playback from the beginning.
                    playButton.ImageIndex = 3;
                }
                break;

                case Vlc.DotNet.Core.Interops.Signatures.MediaStates.Error:
                {
                    MPAiMessageBoxFactory.Show(invalidStateString);
                }
                break;

                default:
                    break;
                }
            }
            catch (Exception exp)
            {
                MPAiMessageBoxFactory.Show(exp.Message);
                Console.WriteLine(exp);
            }
        }
Пример #21
0
 /// <summary>
 /// Calls a dialog box for the user to select a file to overlay.
 /// </summary>
 /// <param name="sender">Automatically generated by Visual Studio.</param>
 /// <param name="e">Automatically generated by Visual Studio.</param>
 private void addFromFileButton_Click(object sender, EventArgs e)
 {
     if (openFileDialog.ShowDialog() == DialogResult.OK)
     {
         if (Path.GetExtension(openFileDialog.FileName).Equals(".wav"))
         {
             File.Copy(openFileDialog.FileName, audioFilePath, true);
             recordingProgressBarLabel.Text = openFileDialog.FileName;
             removeButton.Enabled           = true;
         }
         else
         {
             // If they select a file that is not a wav file, stop them and retry.
             MPAiMessageBoxFactory.Show(wrongFileFormatError);
             addFromFileButton_Click(sender, e);
         }
     }
     // If the user presses cancel, return.
 }
Пример #22
0
 /// <summary>
 /// Functionality to tidy up when recording has stopped.
 /// </summary>
 /// <param name="sender">Automatically generated by Visual Studio.</param>
 /// <param name="e">Automatically generated by Visual Studio.</param>
 void OnRecordingStopped(object sender, StoppedEventArgs e)
 {
     if (InvokeRequired)                                                                  // If it is necessary to invoke this on a different thread
     {
         BeginInvoke(new EventHandler <StoppedEventArgs>(OnRecordingStopped), sender, e); // Send this event to the relevant thread
     }
     else
     {
         Resample();
         recordingProgressBarLabel.Text = outputFileName;
         int newItemIndex = RecordingListBox.Items.Add(outputFileName); // Add the new audio file to the list box
         RecordingListBox.SelectedIndex = newItemIndex;                 // And select it
         SetControlStates(false);                                       // Toggle the record and stop buttons
         if (e.Exception != null)
         {
             DeleteFile();   // Remove the now erroneous file.
             MPAiMessageBoxFactory.Show(string.Format(formatErrorText, e.Exception.Message));
         }
     }
 }
Пример #23
0
 /// <summary>
 /// Functionality to tidy up when recording has stopped.
 /// </summary>
 /// <param name="sender">Automatically generated by Visual Studio.</param>
 /// <param name="e">Automatically generated by Visual Studio.</param>
 void OnRecordingStopped(object sender, StoppedEventArgs e)
 {
     if (InvokeRequired)                                                                  // If it is necessary to invoke this on a different thread
     {
         BeginInvoke(new EventHandler <StoppedEventArgs>(OnRecordingStopped), sender, e); // Send this event to the relevant thread
     }
     else
     {
         SetControlStates(false);    // Toggle the record and stop buttons
         recordingProgressBarLabel.Text = myRecordingText;
         if (e.Exception != null)
         {
             MPAiMessageBoxFactory.Show(string.Format(formatErrorText, e.Exception.Message));
             // Remove the file if it's not valid
             writer.Close();
             recordingProgressBarLabel.Text = noFileText;
             File.Delete(audioFilePath);
             removeButton.Enabled = false;
         }
     }
 }
Пример #24
0
        /// <summary>
        /// Due to the legacy code on the batch files, the enums for voice type don't match the text required in filenames.
        /// This method converts between the two.
        /// </summary>
        /// <param name="voice">A VoiceType enum representing the voice type to convert.</param>
        /// <returns>A string which is the old format for the input enum.</returns>
        private string ConvertDisplayVoiceType(string voice)
        {
            switch (voice)
            {
            case ("Feminine, Kuia Māori"):
                return("oldfemale");

            case ("Masculine, Kaumatua Māori"):
                return("oldmale");

            case ("Feminine, Modern Māori"):
                return("youngfemale");

            case ("Masculine, Modern Māori"):
                return("youngmale");

            default:
                MPAiMessageBoxFactory.Show("Invalid Speaker type!");
                return(null);
            }
        }
Пример #25
0
        /// <summary>
        /// Ensures that the new user is valid, and closes the window.
        /// </summary>
        private void createUser()
        {
            if (userNameBox.Text.Trim() == "")
            {
                MPAiMessageBoxFactory.Show("Username should not be empty! ",
                                           "Oops", MPAiMessageBoxButtons.OK);
                return;
            }
            else if ((passwordBox.Text.Trim() == "") || (confirmPasswordBox.Text.Trim() == ""))
            {
                MPAiMessageBoxFactory.Show("Passwords should not be empty! ",
                                           "Oops", MPAiMessageBoxButtons.OK);
                return;
            }
            else if (passwordBox.Text != confirmPasswordBox.Text)
            {
                MPAiMessageBoxFactory.Show("Passwords do not match! ",
                                           "Oops", MPAiMessageBoxButtons.OK);
                return;
            }

            MPAiUser candidate = getCandidate();

            if (!UserManagement.CreateNewUser(candidate))
            {
                MPAiMessageBoxFactory.Show("User already exists, please use a different name! ",
                                           "Oops", MPAiMessageBoxButtons.OK);
            }
            else
            {
                MPAiMessageBoxFactory.Show("Registration successful! ",
                                           "Congratulations", MPAiMessageBoxButtons.OK);
                UserManagement.WriteSettings();
                LoginScreen loginWindow = (LoginScreen)Owner;      // Only LoginWindow can open this form.
                loginWindow.VisualizeUser(candidate);
                Close();
            }
        }
Пример #26
0
 /// <summary>
 /// Ensures only valid categories are entered, by comparing the text to the names of all categories when focus is lost.
 /// Validation is skipped if the user is uploading a new file, as the category may not be in the database yet.
 /// </summary>
 /// <param name="sender">Automatically generated by Visual Studio.</param>
 /// <param name="e">Automatically generated by Visual Studio.</param>
 private void categoryComboBox_Leave(object sender, EventArgs e)
 {
     // Separate if statements used for code clarity.
     // If the user is uploading a new file, don't enforce this rule.
     if (newFile)
     {
         return;
     }
     // Prevents the user getting stuck when there are no words.
     if (categoryComboBox.Items.Count < 1)
     {
         return;
     }
     foreach (Category w in categoryComboBox.Items)
     {
         if (w.Name.Equals(categoryComboBox.Text))
         {
             return;
         }
     }
     MPAiMessageBoxFactory.Show(categoryNotFoundText);
     categoryComboBox.Focus();
 }
Пример #27
0
        /// <summary>
        /// Sets up the audio device, and the file to record into, adds listeners to the events, starts recording, and toggles the buttons.
        /// </summary>
        private void record()
        {
            try
            {
                var device = (MMDevice)AudioInputDeviceComboBox.SelectedItem;
                if (!(device == null))
                {
                    recordButton.Text          = stopText;
                    recordingProgressBar.Value = 0;

                    device.AudioEndpointVolume.Mute = false;
                    // Use wasapi by default
                    waveIn = new WasapiCapture(device);
                    waveIn.DataAvailable    += OnDataAvailable;
                    dataEvent                = true; // Track whether an event is subscribed to.
                    waveIn.RecordingStopped += OnRecordingStopped;

                    tempFilename = String.Format("{0}-{1:yyy-MM-dd-HH-mm-ss}.wav", UserManagement.CurrentUser.getName(), DateTime.Now);
                    // Initially, outputname is the same as tempfilename
                    outputFileName = tempFilename;
                    writer         = new WaveFileWriter(Path.Combine(tempFolder, tempFilename), waveIn.WaveFormat);
                    waveIn.StartRecording();
                    SetControlStates(true);
                }
                else
                {
                    recordButton.Text = recordText;
                    MPAiMessageBoxFactory.Show(noAudioDeviceText, warningText, MPAiMessageBoxButtons.OK);
                }
            }
            catch (Exception exp)
            {
#if DEBUG
                MPAiMessageBoxFactory.Show(exp.Message, warningText, MPAiMessageBoxButtons.OK);
#endif
            }
        }
Пример #28
0
        /// <summary>
        /// Plays or pauses the video, depending on the VLC player's current state.
        /// </summary>
        private void playVideo()
        {
            using (MPAiModel DBModel = new MPAiModel())
            {
                // The word list only holds proxy objects, as it's context has closed. A database query is needed to get it's recordings.
                Recording rd  = DBModel.Recording.Find(wordsList[currentRecordingIndex].RecordingId);
                Speaker   spk = UserManagement.CurrentUser.Speaker; // Get the speaker from user settings.

                if (rd != null)                                     // If the recording exists
                {
                    SingleFile sf = null;
                    if (rd.Video != null)
                    {
                        sf = rd.Video;
                    }
                    else if (rd.VocalTract != null)
                    {
                        sf = rd.VocalTract;
                    }
                    if (sf == null)
                    {
                        asyncStop();
                        MPAiMessageBoxFactory.Show(noVideoString);
                        return;
                    }
                    filePath = Path.Combine(sf.Address, sf.Name);

                    asyncPlay();
                    playButton.ImageIndex = 3;
                }
                else
                {
                    MPAiMessageBoxFactory.Show(invalidRecordingString);
                }
            }
        }
Пример #29
0
        /// <summary>
        /// Removes the selected items in the database list box from the database and the recordings folder.
        /// </summary>
        /// <param name="sender">Automatically generated by Visual Studio.</param>
        /// <param name="e">Automatically generated by Visual Studio.</param>
        private void toLocalButton_Click(object sender, EventArgs e)
        {
            try
            {
                using (MPAiModel DBModel = new MPAiModel())
                {
                    // Creating a copy of the list box selected items to iterate through
                    List <SingleFile> selectedItemsCopy = new List <SingleFile>();
                    List <SingleFile> allItems          = DBModel.SingleFile.ToList(); // Avoid n+1 selects problem in the next for loop.
                    foreach (SingleFile sf in onDBListBox.SelectedItems)
                    {
                        SingleFile toAdd = allItems.Find(x => x.SingleFileId == sf.SingleFileId);
                        selectedItemsCopy.Add(toAdd);
                    }

                    // For each item in the database list box...
                    foreach (SingleFile sf in selectedItemsCopy)
                    {
                        Recording  rd    = null;
                        NameParser paser = new NameParser();
                        paser.FullName = sf.Name;       // Add the file to the Parser
                        // Use the parser to create the model objects.
                        if (paser.MediaFormat == "audio")
                        {
                            rd = sf.Audio;
                        }
                        else if (paser.MediaFormat == "video")
                        {
                            rd = sf.Video;
                        }
                        Speaker  spk          = rd.Speaker;
                        Word     word         = rd.Word;
                        Category cty          = word.Category;
                        string   existingFile = Path.Combine(sf.Address, sf.Name);
                        File.Delete(existingFile);      // Delete it,
                        DBModel.SingleFile.Remove(sf);  // And remove it from the database.

                        // If the deleted file was:
                        if (rd.Audios.Count == 0 && rd.Video == null)   // The last file attached to a recording, then delete the recording.
                        {
                            DBModel.Recording.Remove(rd);
                        }
                        if (spk.Recordings.Count == 0)                  // The last recording attached to a speaker, then delete the speaker.
                        {
                            DBModel.Speaker.Remove(spk);
                        }
                        if (word.Recordings.Count == 0)                 // The last recording attached to a word, then delete the word.
                        {
                            DBModel.Word.Remove(word);
                        }
                        if (cty.Words.Count == 0)                       // The last word attached to a category, then delete the category.
                        {
                            DBModel.Category.Remove(cty);
                        }
                        DBModel.SaveChanges();
                    }
                }
                populateListBox();
            }
            catch (Exception exp)
            {
                MPAiMessageBoxFactory.Show(exp.Message, deleteFailedText);
            }
        }
Пример #30
0
        /// <summary>
        /// Adds the selected items in the local list box to the database.
        /// </summary>
        /// <param name="sender">Automatically generated by Visual Studio.</param>
        /// <param name="e">Automatically generated by Visual Studio.</param>
        private void toDBButton_Click(object sender, EventArgs e)
        {
            try
            {
                using (MPAiModel DBModel = new MPAiModel())
                {
                    DialogResult renameAction = MPAiMessageBoxFactory.Show(renamewarningText,
                                                                           warningText, MPAiMessageBoxButtons.OKCancel);
                    // If the user selected cancel, don't take any action.
                    if (renameAction.Equals(DialogResult.Cancel))
                    {
                        return;
                    }
                    foreach (FileInfo item in mediaLocalListBox.SelectedItems)  // For each selected item...
                    {
                        FileInfo workingFile = item;

                        // Need to rename file.
                        // If the user wanted to rename them themselves, take the same action as in SpeechRecognitionTest - automatically bring up rename.

                        if (!NameParser.IsFileNameCorrect(workingFile.Name))
                        {
                            // Back up the file to a temporary folder.
                            File.Copy(workingFile.FullName, Path.Combine(AppDataPath.Temp, "Rename_Backup"));

                            //Open the rename dialog
                            RenameFileDialog renameDialog = new RenameFileDialog(workingFile.FullName, true);
                            if (renameDialog.ShowDialog(this).Equals(DialogResult.OK))
                            {
                                // The old file has been changed to this.
                                FileInfo renamedFile = renameDialog.RenamedFile;
                                // Restore the old file, with old name intact, from the backup.
                                File.Move(Path.Combine(AppDataPath.Temp, "Rename_Backup"), workingFile.FullName);
                                // Continue the process with the new file name.
                                workingFile = renamedFile;
                            }
                            else
                            {
                                continue;
                            }
                        }
                        // If the file follows convention (i.e. parts.length == 4), do nothing.

                        NameParser parser = new NameParser();
                        parser.FullName = workingFile.FullName;          // Put the name into the parser
                        // Set the parser address to the audio or video folder as appropriate.
                        if (parser.MediaFormat == "audio")
                        {
                            parser.Address = DirectoryManagement.AudioFolder;
                        }
                        else if (parser.MediaFormat == "video")
                        {
                            parser.Address = DirectoryManagement.VideoFolder;
                        }
                        // Get the file and add it to the database context.
                        DBModel.AddOrUpdateRecordingFile(parser.SingleFile);
                        // Copy the existing local file into the audio/video folder if it wasn't already there.
                        string existingFile = workingFile.FullName;
                        string newFile      = Path.Combine(parser.Address, workingFile.Name);
                        if (!existingFile.Equals(newFile))
                        {
                            File.Copy(existingFile, newFile, true);
                        }
                        DBModel.SaveChanges();
                    }
                }
                populateListBox();
            }
            catch (Exception exp)
            {
                Console.WriteLine(exp.StackTrace);
                MPAiMessageBoxFactory.Show(exp.StackTrace);
            }
            finally
            {
                File.Delete(Path.Combine(AppDataPath.Temp, "Rename_Backup"));
            }
        }