public void Duration_Audio_Correct()
 {
     using (var folder = new TemporaryFolder("FileStatisticsTests"))
     {
         var recording = CreateRecording(folder.Path);
         var info      = MediaFileInfo.GetInfo(recording);
         Assert.AreEqual(1446d, info.Duration.TotalMilliseconds);
     }
 }
        public void BuildCommandLine_CommandLineIncludesAudioBitRateReplacementMarkers_ReturnsRealRate()
        {
            _model.SelectedConversion = FFmpegConversionInfo.CreateForTest("mp3", "-ab {ab}");
            var outputFile = _tempFolder.Combine("test.mp3");

            var mediaInfo = MediaFileInfo.GetInfo(_testAudioFileName);

            Assert.AreEqual("-i \"" + _testAudioFileName + "\" -ab " + mediaInfo.Audio.BitRate + " \"" + outputFile + "\"",
                            _model.BuildCommandLine(outputFile));
        }
Exemple #3
0
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// The input media file may be audio or video.
        /// </summary>
        /// ------------------------------------------------------------------------------------
        public static string GetAudioEncoding(string mediaFilePath)
        {
            var encoding = GetNAudioEncoding(mediaFilePath);

            if (encoding != WaveFormatEncoding.Unknown)
            {
                return(encoding.ToString().Replace("WAVE_FORMAT", "WAV").Replace('_', ' ').ToUpperInvariant());
            }

            var info = MediaFileInfo.GetInfo(mediaFilePath);

            return(info == null ? string.Empty : info.AudioEncoding);
        }
Exemple #4
0
        /// ------------------------------------------------------------------------------------
        public ConvertMediaDlgViewModel(string inputFile, string initialConversionName)
        {
            InputFile = inputFile;

            MediaInfo = MediaFileInfo.GetInfo(inputFile);
            if (MediaInfo == null)
            {
                ConversionState = ConvertMediaUIState.InvalidMediaFile;
            }
            else
            {
                AvailableConversions = FFmpegConversionInfo.GetConversions(inputFile).OrderBy(c => c.Name).ToArray();
                SelectedConversion   = AvailableConversions.FirstOrDefault(c => c.Name == initialConversionName) ?? AvailableConversions[0];

                SetConversionStateBasedOnPresenceOfFfmpegForSayMore();
            }
        }
        public void MPlayerMediaInfo_CreateAudio_ContainsCorrectInfo()
        {
            var tmpfile = GetShortTestAudioFile();

            try
            {
                var minfo = MediaFileInfo.GetInfo(tmpfile);
                Assert.IsFalse(minfo.IsVideo);
                Assert.AreEqual(tmpfile, minfo.MediaFilePath);
                Assert.AreEqual(1.446d, minfo.Duration.TotalSeconds);
                Assert.IsNull(minfo.FullSizedThumbnail);
            }
            finally
            {
                File.Delete(tmpfile);
            }
        }
Exemple #6
0
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// The segmentFileFolder is used for renaming (due to segment boundary changes) and
        /// removing audio segment annotation files that are being created/modified in a
        /// temp. location.
        /// </summary>
        /// ------------------------------------------------------------------------------------
        public TimeTier(string id, string filename)
            : base(id, tier => new AudioWaveFormColumn(tier))
        {
            MediaFileName = filename;
            try
            {
                // SP-835: There was an error accessing media file to determine the duration:
                //  F:\Master\TsakhurProject\Corpus\TsakhurCultureAndLanguageProject\Sessions\TKR-Y-20130708-N03\TKR-Y-20130708-N03_Source.wav
                var shortName = FileSystemUtils.GetShortName(filename);
                _totalTime = MediaFileInfo.GetInfo(shortName).Duration;
            }
            catch (Exception e)
            {
                var msg = LocalizationManager.GetString("SessionsView.Transcription.ErrorAccessingMediaFile",
                                                        "There was an error accessing media file to determine the duration: '{0}'");

                ErrorReport.NotifyUserOfProblem(e, msg, filename);
            }
        }
        public void MPlayerMediaInfo_CreateVideo_ContainsCorrectInfo()
        {
            var tmpfile = GetTestVideoFile();

            try
            {
                var minfo = MediaFileInfo.GetInfo(tmpfile);
                Assert.IsTrue(minfo.IsVideo);
                Assert.AreEqual(tmpfile, minfo.MediaFilePath);
// REVIEW: What to do?				Assert.AreEqual(5.49f, (float)Math.Round(minfo.StartTime, 2));
                Assert.AreEqual(9.5f, (float)Math.Round(minfo.DurationInSeconds, 2));
                Assert.AreEqual(new Size(320, 240), minfo.Video.PictureSize);
                Assert.IsNotNull(minfo.FullSizedThumbnail);
            }
            finally
            {
                File.Delete(tmpfile);
            }
        }
        /// ------------------------------------------------------------------------------------
        public IEnumerable <AnnotationSegment> FixUpLabelInfo(List <AnnotationSegment> segments)
        {
            for (int i = 0; i < segments.Count; i++)
            {
                if (segments[i].End > segments[i].Start)
                {
                    continue;
                }

                // At this point, we know the stop location is zero. For all labels but the
                // last label, the stop position will be the start position of the next label.
                // For the last label, the stop position is assumed to be the end of the file.
                if (i < segments.Count - 1)
                {
                    segments[i].End = segments[i + 1].Start;
                }
                else if (i == segments.Count - 1 && _mediaFile != null)
                {
                    var mediaInfo = MediaFileInfo.GetInfo(_mediaFile);

                    if (segments[i].Start.Equals(mediaInfo.DurationInSeconds))
                    {
                        segments.RemoveAt(i);
                    }
                    else
                    {
                        segments[i].End = mediaInfo.DurationInSeconds;
                    }
                }
            }

            // If the label file didn't have a label at the beginning of the
            // file (i.e. offset zero), treat offset zero as an implicit label.
            if (segments.Count > 0 && segments[0].Start > 0)
            {
                segments.Insert(0, new AnnotationSegment {
                    Start = 0, End = segments[0].Start
                });
            }

            return(segments);
        }
Exemple #9
0
        /// ------------------------------------------------------------------------------------
        public void LoadFile(string filename, float playbackStartPosition, float playbackLength)
        {
            ShutdownMPlayerProcess();

            // On Windows, We can't get unicode over the command-line barrier, so
            // instead create 8.3 filename, which, happily, will have no non-english characters
            // for any part of the path.
            filename = FileSystemUtils.GetShortName(filename);

            if (string.IsNullOrEmpty(filename))
            {
                throw new ArgumentException(LocalizationManager.GetString(
                                                "CommonToMultipleViews.MediaPlayer.MediaFileNotSpecifiedMsg",
                                                "Media player file name has not been specified."));
            }

            if (!File.Exists(filename))
            {
                throw new FileNotFoundException(String.Format(LocalizationManager.GetString(
                                                                  "CommonToMultipleViews.MediaPlayer.MediaFileNotFoundMsg",
                                                                  "Media file not found: {0}"), filename), filename);
            }

            MediaInfo = MediaFileInfo.GetInfo(filename);
            if (MediaInfo == null)
            {
                throw new FileFormatException(String.Format(LocalizationManager.GetString(
                                                                "CommonToMultipleViews.MediaPlayer.InvalidMediaFile",
                                                                "File does not appear to be a valid media file: {0}"), filename));
            }

            MediaFile             = filename.Replace('\\', '/');
            PlaybackStartPosition = playbackStartPosition;
            PlaybackLength        = playbackLength;
            OnMediaQueued();

            if (_formMPlayerOutputLog != null)
            {
                _formMPlayerOutputLog.Clear();
            }
        }
Exemple #10
0
        /// ------------------------------------------------------------------------------------
        private void SaveFromSegments(IEnumerable <AnnotationSegment> segments)
        {
            RemoveTimeSlots();
            RemoveAnnotationsFromTier(TextTier.ElanTranscriptionTierId);
            RemoveAnnotationsFromTier(TextTier.ElanTranslationTierId);

            var mediaInfo = MediaFileInfo.GetInfo(_mediaFileName);

            // Don't add any segments that extend beyond the end of the media file.
            foreach (var seg in segments.Where(s => s.Start <= mediaInfo.Audio.DurationInSeconds))
            {
                if (seg.End > mediaInfo.Audio.DurationInSeconds)
                {
                    seg.End = mediaInfo.Audio.DurationInSeconds;
                }

                CreateTranscriptionAnnotationElement(seg);
            }

            Save();
        }
Exemple #11
0
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Extracts the audio stream from the specified video file and writes it to a wav
        /// file (i.e. raw PCM).
        /// </summary>
        /// ------------------------------------------------------------------------------------
        public static ConversionResult CreatePcmAudioFromMediaFile(string mediaInPath,
                                                                   string audioOutPath, WaveFormat preferredOutputFormat, out string output)
        {
            output = null;

            // problem with non-ascii characters, convert to 8.3 path
            mediaInPath = FileSystemUtils.GetShortName(mediaInPath);

            // output to temp file, with 8.3 path
            var tempFile = Path.GetTempFileName();

            mediaInPath = mediaInPath.Replace('\\', '/');
            if (preferredOutputFormat == null)
            {
                var info = MediaFileInfo.GetInfo(mediaInPath);
                if (info == null)
                {
                    return(ConversionResult.ConversionFailed);
                }
                preferredOutputFormat = new WaveFormat(info.SamplesPerSecond, info.BitsPerSample, info.Channels);
            }
            var args = GetArgumentsToCreatePcmAudio(mediaInPath, tempFile, preferredOutputFormat);
            var finishedProcessing = false;
            var result             = ConversionResult.InProgress;
            var outputBuilder      = new StringBuilder();
            var debugOutput        = Application.OpenForms.OfType <ILogger>().FirstOrDefault();

            var prs = StartProcessToMonitor(args,
                                            (s, e) =>
            {
                if (e.Data != null)
                {
                    lock (LockToken)
                    {
                        outputBuilder.AppendLine(e.Data);
                    }
                    if (debugOutput != null)
                    {
                        debugOutput.AddText(e.Data);
                    }
                }
                finishedProcessing |= (e.Data == "Exiting... (End of file)");                                 // OR-equal (|=) prevents subsequent blank line from setting it back to false.
            },
                                            (s, e) =>
            {
                if (e.Data != null)
                {
                    lock (LockToken)
                    {
                        outputBuilder.AppendLine(e.Data);
                    }
                    if (debugOutput != null)
                    {
                        debugOutput.AddText(e.Data);
                    }
                    if (e.Data == "Seek failed")
                    {
                        result |= ConversionResult.PossibleError;
                    }
                    else if (e.Data.StartsWith("Failed to open"))
                    {
                        result = ConversionResult.ConversionFailed;
                    }
                }
            });

            if (prs == null)
            {
                return(ConversionResult.ConversionFailed);
            }

            while (!finishedProcessing && result != ConversionResult.ConversionFailed)
            {
                Application.DoEvents();
            }

            prs.Dispose();
            if (result != ConversionResult.ConversionFailed)
            {
                // copy to requested file name
                if (File.Exists(tempFile))
                {
                    File.Copy(tempFile, audioOutPath);
                }

                result |= ConversionResult.FinishedConverting;

                lock (LockToken)
                {
                    output = outputBuilder.ToString();
                }
            }

            // delete the temp file
            if (File.Exists(tempFile))
            {
                File.Delete(tempFile);
            }

            return(result);
        }