async public Task<bool> FixOrientationAsync(MediaFile file) { if (file == null) return false; try { var filePath = file.Path; var orientation = GetRotation(filePath); if (!orientation.HasValue) return false; Bitmap bmp = RotateImage(filePath, orientation.Value); var quality = 90; using (var stream = File.Open(filePath, FileMode.OpenOrCreate)) await bmp.CompressAsync(Bitmap.CompressFormat.Png, quality, stream); bmp.Recycle(); return true; } catch (Exception ex) { //ex.Report(); //Extension method for Xamarin.Insights return false; } }
async Task Recognise (MediaFile result) { if (result.Source == null) return; try { activityIndicator.IsRunning = true; if (!_tesseract.Initialized) { var initialised = await _tesseract.Init ("eng"); if (!initialised) return; } if (!await _tesseract.SetImage (result.Source)) return; } catch (Exception ex) { DisplayAlert ("Error", ex.Message, "Cancel"); } finally { activityIndicator.IsRunning = false; } TextLabel.Text = _tesseract.Text; var words = _tesseract.Results (PageIteratorLevel.Word); var symbols = _tesseract.Results (PageIteratorLevel.Symbol); var blocks = _tesseract.Results (PageIteratorLevel.Block); var paragraphs = _tesseract.Results (PageIteratorLevel.Paragraph); var lines = _tesseract.Results (PageIteratorLevel.Textline); }
/// <summary> /// Extracts season and episode number by using some regexes specified in patterns /// </summary> /// <param name="ie">Candidate which should be processed</param> /// <param name="patterns">Patterns to be used for recognition, supply these for speed reasons?</param> public static void ExtractSeasonAndEpisode(MediaFile ie, string[] patterns) { string strSeason = ""; string strEpisode = ""; Match m = null; int episode = -1; int season = -1; log.Debug("Extracting season and episode from " + ie.FilePath + Path.DirectorySeparatorChar + ie.Filename); //[MOVIES_TAGS_TO_REMOVE_LIST_KEY] and (CRCXXXXX) are removed for recognition, since they might produce false positives string cleanedname = Regex.Replace(ie.Filename, "\\[.*?\\]|\\(.{8}\\)", ""); foreach (string pattern in patterns) { //Try to match. If it works, get the season and the episode from the match m = Regex.Match(cleanedname, pattern, RegexOptions.IgnoreCase | RegexOptions.RightToLeft); if (m.Success) { log.Debug("This pattern produced a match: " + pattern); strSeason = ""; strEpisode = ""; //ignore numbers like 2063, chance is higher they're a year than a valid season/ep combination if (Int32.Parse(m.Groups["Season"].Value + m.Groups["Episode"].Value) > 2000 && (m.Groups["Season"].Value + m.Groups["Episode"].Value).StartsWith("20")) { continue; } try { strSeason = Int32.Parse(m.Groups["Season"].Value).ToString(); } catch (FormatException) { } try { strEpisode = Int32.Parse(m.Groups["Episode"].Value).ToString(); } catch (FormatException) { } //Fix for .0216. notation for example, 4 numbers should always be recognized as %S%S%E%E (IF THEY ARENT A YEAR!) if (strEpisode.Length == 3 && strSeason.Length == 1) { strSeason += strEpisode[0]; strEpisode = strEpisode.Substring(1); if (strSeason[0] == '0') { strSeason = strSeason.Substring(1); } } try { episode = Int32.Parse(strEpisode); } catch { log.Debug("Cannot parse found episode: " + strEpisode); } try { season = Int32.Parse(strSeason); } catch { log.Debug("Cannot parse found season: " + strSeason); } if ((ie.Filename.ToLower().Contains("720p") && season == 7 && episode == 20) | (ie.Filename.ToLower().Contains("1080p") && season == 10 && episode == 80)) { season = -1; episode = -1; continue; } ie.SeasonNr = season; ie.EpisodeNr = episode; return; } } }
private void ConvertMediaFile(MediaFile mediaFile, FileToSyncItemConfiguration path) { if (File.Exists(path.Destination.FullPath + PathUtils.Extension)) { SyncItem parent = SyncItemProvider.GetSyncItem(path.Destination.FullPath + PathUtils.Extension); string name = String.IsNullOrEmpty(Path.GetFileNameWithoutExtension(mediaFile.Name)) ? mediaFile.Name : Path.GetFileNameWithoutExtension(mediaFile.Name); string syncItemPath = Path.Combine(path.Destination.FullPath, name + PathUtils.Extension); if (File.Exists(syncItemPath)) { SyncItem syncItem = SyncItemProvider.GetSyncItem(syncItemPath); if (mediaFile.Blob != syncItem.SharedValues[FileTemplateFields.Blob.FieldId]) { syncItem.AttachMediaFile(new FileInfo(mediaFile.FilePath)); syncItem = _serializationManager.UpdateStatistics(syncItem); SyncItemProvider.SaveSyncItem(syncItem, syncItemPath); } } else { SyncItem item = _serializationManager.CreateSyncMediaItem(parent.ItemPath, path.Destination.Database, parent.ID, mediaFile.FilePath); SyncItemProvider.SaveSyncItem(item, syncItemPath); } } }
// Returns the value of the FilePath for a given item // ** Example ** // Given: MediaFile: Artist: Artist1, Album: Album1, Genre: Genre1, FileType: MP3, FileName: SongTitle.mp3 // Order: FileType -> Genre -> Artist -> Album // (External usage) Base Directory: C:/Music // Returns: MP3/Genre1/Artist1/Album1/ // Helps Create: C:/Music/MP3/Genre1/Artist1/Album1/SongTitle.mp3 public string FilePath( MediaFile mf ) { string filePath = ""; foreach ( string folder in folderStructure.FolderCategories ) { if ( folder == "Artist" ) { filePath += mf.Artist + @"/"; } if ( folder == "Album" ) { filePath += mf.Album + @"/"; } if ( folder == "FileType" ) { filePath += mf.FileType.Substring( 1, mf.FileType.Length - 1 ).ToUpper( ) + @"/"; } if ( folder == "Genre" ) { filePath += mf.Genre + @"/"; } } return filePath; }
public static Dictionary<string, string> GetVideoInfo(string fileName) { var dic = new Dictionary<string, string>(); var mediaFile = new MediaFile(fileName); dic.Add(VideoInfoConstants.FileName, mediaFile.Name); dic.Add(VideoInfoConstants.Format, mediaFile.General.Format); dic.Add(VideoInfoConstants.Duration, mediaFile.General.DurationString); dic.Add(VideoInfoConstants.Bitrate, mediaFile.General.Bitrate.ToInvariantString()); if (mediaFile.Audio.Count > 0) { dic.Add(VideoInfoConstants.AudioFormat, mediaFile.Audio[0].Format); dic.Add(VideoInfoConstants.AudioBitrate, mediaFile.Audio[0].Bitrate.ToInvariantString()); dic.Add(VideoInfoConstants.AudioChannels, mediaFile.Audio[0].Channels.ToInvariantString()); dic.Add(VideoInfoConstants.AudioSamplingRate, mediaFile.Audio[0].SamplingRate.ToInvariantString()); } if (mediaFile.Video.Count > 0) { dic.Add(VideoInfoConstants.VideoFormat, mediaFile.Video[0].Format); dic.Add(VideoInfoConstants.VideoBitrate, mediaFile.Video[0].Bitrate.ToInvariantString()); dic.Add(VideoInfoConstants.VideoFrameRate, mediaFile.Video[0].FrameRate.ToInvariantString()); dic.Add(VideoInfoConstants.VideoFrameSize, mediaFile.Video[0].FrameSize); } return dic; }
public ObservableCollection<MediaFile> CreateViewable( string folderPath ) { if ( !Directory.Exists( folderPath ) ) return null; fileLoader.ReadFolder( folderPath ); foreach ( string file in fileLoader.Files ) { try { var mf = new MediaFile( TagLib.File.Create( file ) ); fullFilePathToMediaFile.Add( file, mf ); int lastSlashOffset = file.LastIndexOf( "\\" ) + 1; string partialFile = file.Substring( lastSlashOffset ); partialFilePathToMediaFile.Add( partialFile, mf ); ocMediaFiles.Add( mf ); } catch ( Exception ex ) { exceptionList.Add( new Tuple<string, string>( ex.Message + System.Environment.NewLine + ex.StackTrace, file ) ); } } return ocMediaFiles; }
/// <summary> /// Open file for playing /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void MenuOpenFile_OnClick(object sender, RoutedEventArgs e) { try { var objDialog = new OpenFileDialog() { Filter = "Media files| *.mp4; *.avi; *.mp3; *.wav; *.pl" }; bool? result = objDialog.ShowDialog(); if(result == true) { var objFileInfo = new FileInfo(objDialog.FileName); //rewrite current play list _PlayList = new PlayList(); //if we opened playlist if(objFileInfo.Extension == ".pl") { _PlayList.Open(objDialog.FileName); UpdatePlayListView(); } else { //if we opened standart media file var objMediaFile = new MediaFile(objFileInfo); _PlayList.MediaFiles.Add(objMediaFile); ListBoxPlayList.Items.Add(objMediaFile); } ListBoxPlayList.SelectedIndex = 0; ListBoxPlayList_OnMouseDoubleClick(sender, null); } } catch(Exception ex) { MessageBox.Show(ex.Message); } }
private void LoadButton_Click(object sender, RoutedEventArgs e) { try { OpenFileDialog openFile = new OpenFileDialog { Filter = "Video files (*.mp4)|*.mp4", FilterIndex = 1, RestoreDirectory = true }; if (openFile.ShowDialog() == true) { Screen.Source = new Uri(openFile.FileName); Screen.LoadedBehavior = MediaState.Pause; inputFile = new MediaFile {Filename = openFile.FileName}; } _firstPlay = true; } catch (Exception) { MessageBox.Show("Failed load video"); } }
public async Task<MediaFile> UploadMediaAsync(MediaUpload upload) { var blobId = await GetNewBlobIdAsync(upload.ContentType); var url = string.Format("{0}/content/{1}", BaseApiUrl, blobId); using (var client = new HttpClient()) { var response = await client.PostAsync(url, upload.Content); if (!response.IsSuccessStatusCode) return null; } var media = new MediaFile { BlobId = blobId, ContentSize = upload.ContentSize, ContentType = upload.ContentType, Uploaded = DateTime.UtcNow }; var inserted = _mediaRepository.Insert(media); _unit.Commit(); Log.InfoFormat("Uploaded media to FooCDN. Id={0} BlobId={1} ContentSize={2} ContentType={3} StorageType={4}", media.Id, media.BlobId, media.ContentSize, media.ContentType, media.StorageType); return inserted; }
public async Task<IMediaFile> PickPhotoAsync() { Debug.WriteLine("PickPhotoAsync: starting"); // setup a task to get the results back from the delegate var mediaInfoTask = new TaskCompletionSource<NSDictionary>(); // setup a UI Picker to show photos var picker = new UIImagePickerController(); picker.SourceType = UIImagePickerControllerSourceType.PhotoLibrary; picker.MediaTypes = new string[] { UTType.Image }; picker.AllowsEditing = false; picker.Delegate = new MediaDelegate { InfoTask = mediaInfoTask }; // iPad should display the picker in a popover if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) picker.ModalInPopover = true; var vc = GetViewController(); Debug.WriteLine("PickPhotoAsync: displaying photo picker"); vc.PresentViewController(picker, true, null); // wait to get the results back Debug.WriteLine("PickPhotoAsync: waiting for selected photo"); var info = await mediaInfoTask.Task; var assetUrl = info[UIImagePickerController.ReferenceUrl] as NSUrl; Debug.WriteLine("PickPhotoAsync: photo selected {0}", assetUrl); var mediaFile = new MediaFile {Path = assetUrl.ToString()}; Debug.WriteLine("PickPhotoAsync: returning created media file"); return mediaFile; }
public void Can_CutVideo() { string filePath = @"{0}\Cut_Video_Test.mp4"; string outputPath = string.Format(filePath, Path.GetDirectoryName(_outputFilePath)); var inputFile = new MediaFile { Filename = _inputFilePath }; var outputFile = new MediaFile { Filename = outputPath }; using (var engine = new Engine()) { engine.ConvertProgressEvent += engine_ConvertProgressEvent; engine.ConversionCompleteEvent += engine_ConversionCompleteEvent; engine.GetMetadata(inputFile); ConversionOptions options = new ConversionOptions(); options.CutMedia(TimeSpan.FromSeconds(30), TimeSpan.FromSeconds(25)); engine.Convert(inputFile, outputFile, options); engine.GetMetadata(outputFile); } Assert.That(File.Exists(outputPath)); // Input file is 33 seconds long, seeking to the 30th second and then // attempting to cut another 25 seconds isn't possible as there's only 3 seconds // of content length, so instead the library cuts the maximumum possible. }
public void FileController_UpdateSEO_ShouldReturnChangesSaved() { FileController fileController = GetFileController(); var mediaFile = new MediaFile(); fileController.UpdateSEO(mediaFile, "test", "test").Should().Be("Changes saved"); }
public IEnumerable<IMediaFile> GetMediaForProjectByType(int projectId, FileType type) { var wikiFiles = WikiFile.CurrentFiles(projectId); var mediaFiles = new List<MediaFile>(); foreach (var wikiFile in wikiFiles) { var mediaFile = new MediaFile { Current = wikiFile.Current, Archived = wikiFile.Archived, CreateDate = wikiFile.CreateDate, Name = wikiFile.Name, Id = wikiFile.Id, CreatedBy = wikiFile.CreatedBy, DotNetVersion = wikiFile.DotNetVersion, Downloads = wikiFile.Downloads, FileType = (FileType)Enum.Parse(typeof(FileType), wikiFile.FileType), FileVersion = wikiFile.NodeVersion, Path = wikiFile.Path, RemovedBy = wikiFile.RemovedBy, SupportsMediumTrust = false, UmbVersion = wikiFile.Versions, Verified = wikiFile.Verified }; if (mediaFiles.Contains(mediaFile) == false) mediaFiles.Add(mediaFile); } return mediaFiles; }
protected override string GenerateKey(MediaFile videoFile, ThumbnailGenerationOptions options) { return string.Format("{0}_{1}_{2}", videoFile.Id, options.PointInTime.ResolveAgainst(videoFile.Duration).ToTicksString(), options.ImageSize); }
public override bool BuildFrame(MediaFile file, MediaFrame mediaFrame, Stream buffer) { if (mediaFrame.IsBinaryHeader) { buffer.Write(_videoCodecHeaderInit,0, _videoCodecHeaderInit.Length); } else { if (mediaFrame.IsKeyFrame) { // video key frame buffer.Write(_videoCodecHeaderKeyFrame, 0,_videoCodecHeaderKeyFrame.Length); } else { //video normal frame buffer.Write(_videoCodecHeader, 0, _videoCodecHeader.Length); } mediaFrame.CompositionOffset = IPAddress.HostToNetworkOrder(mediaFrame.CompositionOffset & 0x00ffffff) >> 8; buffer.Write(BitConverter.GetBytes(mediaFrame.CompositionOffset), 0, 3); } return base.BuildFrame(file, mediaFrame, buffer); }
protected override Image GenerateImage(MediaFile videoFile, ThumbnailGenerationOptions options) { var baseImage = _thumbnailGenerator.Generate(videoFile, options).Image; var sizedImage = ResizeImage(baseImage, options.ImageSize.Width, options.ImageSize.Height); return sizedImage; }
public void InstantiateCorrectly() { byte[] content = new byte[5]; Guid id = new Guid(); MediaFile mediaFile = new MediaFile {Content = content, Id = id}; Assert.AreEqual(content, mediaFile.Content); Assert.AreEqual(id, mediaFile.Id); }
public void LoadImage(string fileName) { var buf= new MediaFile(fileName); if (ByteToImageConverter.IsFileImage(buf)) { this.File = buf; } }
public ImageItemWindow(MediaFile file) { this.File = file; this.SavedFile = file; InitializeComponent(); this.DataContext = this; }
public void ConstructWithManagedLifespanAndDispose() { File.Copy("image1.jpg", "temp.jpg"); var file = new MediaFile("temp.jpg", true); Assert.IsTrue(File.Exists(file.FileName)); file.Dispose(); Assert.IsFalse(File.Exists(file.FileName)); }
private ThumbnailImage GenerateThumbnail(MediaFile videoFile, ThumbnailGenerationOptions options, string thumbnailFile) { _ffmpeg.CreateThumbnailImage(videoFile.Path, options.PointInTime.ResolveAgainst(videoFile.Duration), thumbnailFile); var image = _fileManager.LoadImage(thumbnailFile); return new ThumbnailImage(image, options.ImageType); }
/// <summary> /// Extracts season and episode number by using some regexes from config file /// </summary> /// <param name="ie">Candidate which should be processed</param> public static void ExtractSeasonAndEpisode(MediaFile ie) { string[] patterns = Helper.ReadProperties(AppProperties.EPISODE_IDENTIFIER_PATTERNS_KEY); for (int i = 0; i < patterns.Length; i++) { patterns[i] = RegexConverter.toRegex(patterns[i]); } ExtractSeasonAndEpisode(ie, patterns); }
public bool Equals(MediaFile o) { return o != null && base.Equals((Node)o) && this.Artist == o.Artist && this.Album == o.Album && this.Title == o.Title; }
public DateTime UpdateCreationDate(MediaFile mediaFile) { var originalCreationDate = GetOriginalCreationDate(mediaFile); UpdateCreationDate(mediaFile, originalCreationDate); return originalCreationDate; }
public MediaPickedEventArgs(int id, bool cancelled, MediaFile media = null) { RequestId = id; Cancelled = cancelled; if (!cancelled && media == null) throw new ArgumentNullException("media"); Media = media; }
public void FileController_Delete_CallsDeleteFileOnFileService() { FileController fileController = GetFileController(); var mediaFile = new MediaFile(); mediaFile.MediaCategory = new MediaCategory{Id = 1}; fileController.Delete_POST(mediaFile); A.CallTo(() => fileAdminService.DeleteFile(mediaFile)).MustHaveHappened(); }
public void LoadFiles(string[] path) { foreach (string p in path) { MediaFile f = new MediaFile(); f.LoadFile(p); this.Files.Add(f); } }
public void FileController_UpdateSEO_IfErrorIsThrownOnSaveReturnValueContainsMessage() { FileController fileController = GetFileController(); var mediaFile = new MediaFile(); A.CallTo(() => fileAdminService.SaveFile(mediaFile)).Throws(new Exception("Test exception")); fileController.UpdateSEO(mediaFile, "test-title", "test-description") .Should() .Be("There was an error saving the SEO values: Test exception"); }
private static string GetMetadata(MediaFile inputFile) { return(string.Format("-i \"{0}\" ", inputFile.Filename)); }
public FacesViewModel(MediaFile photo, IEnumerable <DetectedFace> faces) { Faces = faces.Select(f => new FaceViewModel(photo, f)); SelectedFace = Faces.First(); }
void OnDeleteImageTapped(object sender, EventArgs args) { this.imagefile = null; image.Source = ""; imgDelete.IsVisible = false; }
private void NewSlideShow_events(object sender, EventArgs e) { MediaFile file = (e as MediaEventArg).MediaFile; photoWindow.Update(file); }
public IncidenceReport(string reporttype) { ObtainDeviceLocation(); InitializeComponent(); var mainDisplayInfo = DeviceDisplay.MainDisplayInfo; // Width (in pixels) var width = mainDisplayInfo.Width; var height = mainDisplayInfo.Height; var deviceManufacturer = DeviceInfo.Manufacturer; var density = mainDisplayInfo.Density; if (height <= 1440 && density >= 2.25) { tagHeight.HeightRequest = 30; overallRowSpacing.RowSpacing = 5; frameType.HeightRequest = 34; FrameDescription.HeightRequest = 34; FrameName.HeightRequest = 34; FramePhoneNumber.HeightRequest = 34; mainGridPadding.Padding = 20; confirmationtext.FontSize = 12; FrameName.HeightRequest = 36; frameType.HeightRequest = 36; FrameDescription.HeightRequest = 36; FramePhoneNumber.HeightRequest = 36; lblType.FontSize = 12; lblDescription.FontSize = 12; lblReporterName.FontSize = 12; lblPhoneNumber.FontSize = 12; } else if (height < 1560) { //Set the height of the blue bar tagHeight.HeightRequest = 30; overallRowSpacing.RowSpacing = 5; frameType.HeightRequest = 35; FrameDescription.HeightRequest = 35; FrameName.HeightRequest = 35; FramePhoneNumber.HeightRequest = 35; } else if (height >= 1560 && density == 0) { //Set the height of the blue bar tagHeight.HeightRequest = 30; overallRowSpacing.RowSpacing = 5; frameType.HeightRequest = 35; FrameDescription.HeightRequest = 35; FrameName.HeightRequest = 35; FramePhoneNumber.HeightRequest = 35; } else if (height >= 1560) { } MessagingCenter.Subscribe <Object, MediaFile>(this, "finish", (arg, source) => { // capturedImage.Source = ImageSource.FromStream(() => source.GetStream()); _received = source; if (_received != null) { // ImgText.Text = "Image Successfully Captured"; // ImgText.IsVisible = true; // capturedImage.Source = "checkmark"; // capturedImage.IsVisible = true; // chkAgree.IsChecked = false; } }); lblReportType.Text = reporttype.ToUpper(); if (reporttype == "Fault") { var pickerList = new List <string>(); pickerList.Add("Voltage Fluctuation"); pickerList.Add("Fallen/Bent Poles"); pickerList.Add("Transformer Fault"); pickerList.Add("Phase Failure"); PickType.ItemsSource = pickerList; this.BindingContext = this; } else if (reporttype == "Outage") { var pickerList = new List <string>(); pickerList.Add("Prolonged Outage Data"); PickType.ItemsSource = pickerList; this.BindingContext = this; } else if (reporttype == "Complain") { // PopupNavigation.Instance.PushAsync(new AccountVerification()); var pickerList = new List <string>(); pickerList.Add("Burnt Meter"); pickerList.Add("Tamper Code"); pickerList.Add("Stolen Meter"); pickerList.Add("Payment Issues"); pickerList.Add("Vending Issues"); pickerList.Add("Wrong Disconnection"); PickType.ItemsSource = pickerList; this.BindingContext = this; } else if (reporttype == "Hazard") { var pickerList = new List <string>(); pickerList.Add("Vegetation Interference"); pickerList.Add("Live Cable Snapping"); PickType.ItemsSource = pickerList; this.BindingContext = this; } else if (reporttype == "Whistle") { var pickerList = new List <string>(); pickerList.Add("Extortion"); pickerList.Add("Bills not Distributed"); pickerList.Add("Paying to Marketer"); pickerList.Add("Paying to Illegal 3rd Party"); pickerList.Add("Double Feeding"); pickerList.Add("Illegal Disconnection"); pickerList.Add("Meter Byepass"); pickerList.Add("Meter Tampering"); PickType.ItemsSource = pickerList; this.BindingContext = this; } //Task.Run(ObtainDeviceLocation); }
public static FolderObject WalkDirectoryTree(this FolderObject folderObject, DirectoryInfo root) { folderObject.Name = root.Name; folderObject.FullPath = root.FullName; FileInfo[] files = null; try { files = root.GetFiles("*.*"); } catch (UnauthorizedAccessException e) { Console.WriteLine(e.Message); } catch (DirectoryNotFoundException e) { Console.WriteLine(e.Message); } if (files != null && files.Any()) { foreach (var fi in files) { FileObject file; try { using (Stream stream = File.OpenRead(fi.FullName)) { using (var srcImg = Image.FromStream(stream, false, false)) { file = new FileObject(fi.Name, srcImg.Width.ToString(), srcImg.Height.ToString()); } } } catch (Exception) // it is a video ! { var inputFile = new MediaFile { Filename = fi.FullName }; using (var engine = new Engine()) { engine.GetMetadata(inputFile); } if (inputFile.Metadata == null) { continue; } if (inputFile.Metadata.VideoData == null) { continue; } var size = inputFile.Metadata.VideoData.FrameSize.Split('x'); file = new FileObject(fi.Name, size.First(), size.Last()); } folderObject.Files.Add(file); } } var subDirs = root.GetDirectories(); if (subDirs.Any()) { foreach (var dirInfo in subDirs) { folderObject.Folders.Add(WalkDirectoryTree(new FolderObject(), dirInfo)); } } return(folderObject); }
public bool FileNeedsRemux(MediaFile file) { return(GStreamer.FileNeedsRemux(file)); }
public ViewMediaInfoForm(string path) { InitializeComponent(); Icon = Gui.Icon; wb_info.PreviewKeyDown += OnBrowserPreviewKeyDown; var mediaFile = new MediaFile(path); var mi = new MediaInfo(); mi.Open(path); var lines = new List <string>(); { lines.Add("<!doctype html>"); lines.Add("<html>"); lines.Add("<head>"); lines.Add("<style>* { padding: 0px; margin: 0px; font-family:tahoma; } body { width: 700px; background: #fff; margin: 0 auto; } table { width: 700px; font-size: 12px; border-collapse: collapse; } td { width: 570px; padding: 5px; border-bottom: 1px dotted #1562b6; word-wrap: break-word; } td:first-child { width: 130px; border-right: 1px solid #1562b6; } .thead { font-size: 15px; color: #1562b6; padding-top: 25px; border: 0px !important; border-bottom: 2px solid #1562b6 !important; } .no-padding { padding-top: 0px !important; }</style>"); lines.Add("</head>"); lines.Add("<body>"); lines.Add("<table border='0' cellspacing='0' cellpadding='0'>"); lines.Add("<tr><td class='thead no-padding' colspan='2'><b>General</b></td></tr>"); lines.Add(string.IsNullOrEmpty(mediaFile.miGetString("UniqueID/String")) ? string.Empty : string.Format("<tr><td>Unique ID:</td><td>{0}</td></tr>", mediaFile.miGetString("UniqueID/String"))); lines.Add(string.IsNullOrEmpty(mediaFile.miGetString("Movie")) ? string.Empty : string.Format("<tr><td>Movie name:</td><td>{0}</td></tr>", mediaFile.miGetString("Movie"))); lines.Add(string.IsNullOrEmpty(mediaFile.miGetString("CompleteName")) ? string.Empty : string.Format("<tr><td>Complete name:</td><td>{0}</td></tr>", mediaFile.miGetString("CompleteName"))); lines.Add(string.IsNullOrEmpty(mediaFile.miGetString("Format")) ? string.Empty : string.Format("<tr><td>Format:</td><td>{0}</td></tr>", mediaFile.miGetString("Format"))); lines.Add(string.IsNullOrEmpty(mediaFile.miGetString("Format_Version")) ? string.Empty : string.Format("<tr><td>Format version:</td><td>{0}</td></tr>", mediaFile.miGetString("Format_Version"))); lines.Add(string.IsNullOrEmpty(mediaFile.miGetString("FileSize/String")) ? string.Empty : string.Format("<tr><td>File size:</td><td>{0}</td></tr>", mediaFile.miGetString("FileSize/String"))); lines.Add(string.IsNullOrEmpty(mediaFile.miGetString("Duration/String")) ? string.Empty : string.Format("<tr><td>Duration:</td><td>{0}</td></tr>", mediaFile.miGetString("Duration/String"))); lines.Add(string.IsNullOrEmpty(mediaFile.miGetString("OverallBitRate/String")) ? string.Empty : string.Format("<tr><td>Overall bitrate:</td><td>{0}</td></tr>", mediaFile.miGetString("OverallBitRate/String"))); lines.Add(string.IsNullOrEmpty(mediaFile.miGetString("Encoded_Date")) ? string.Empty : string.Format("<tr><td>Encoded date:</td><td>{0}</td></tr>", mediaFile.miGetString("Encoded_Date"))); lines.Add(string.IsNullOrEmpty(mediaFile.miGetString("Encoded_Application")) ? string.Empty : string.Format("<tr><td>Writing application:</td><td>{0}</td></tr>", mediaFile.miGetString("Encoded_Application"))); lines.Add(string.IsNullOrEmpty(mediaFile.miGetString("Encoded_Library/String")) ? string.Empty : string.Format("<tr><td>Writing library:</td><td>{0}</td></tr>", mediaFile.miGetString("Encoded_Library/String"))); } lines.Add("<tr><td class='thead' colspan='2'><b>Video</b></td></tr>"); foreach (var info in mediaFile.Video) { lines.Add(string.Format("<tr><td>ID:</td><td>{0}</td></tr>", info.Value.miGetString("ID/String"))); lines.Add(string.IsNullOrEmpty(info.Value.miGetString("Title")) ? string.Empty : string.Format("<tr><td>Title:</td><td>{0}</td></tr>", info.Value.miGetString("Title"))); lines.Add(string.IsNullOrEmpty(info.Value.miGetString("Format")) ? string.Empty : string.Format("<tr><td>Format:</td><td>{0}</td></tr>", info.Value.miGetString("Format"))); lines.Add(string.IsNullOrEmpty(info.Value.miGetString("Format/Info")) ? string.Empty : string.Format("<tr><td>Format info:</td><td>{0}</td></tr>", info.Value.miGetString("Format/Info"))); lines.Add(string.IsNullOrEmpty(info.Value.miGetString("Format_Profile")) ? string.Empty : string.Format("<tr><td>Format profile:</td><td>{0}</td></tr>", info.Value.miGetString("Format_Profile"))); lines.Add(string.IsNullOrEmpty(info.Value.miGetString("Format_Settings")) ? string.Empty : string.Format("<tr><td>Format settings:</td><td>{0}</td></tr>", info.Value.miGetString("Format_Settings"))); lines.Add(string.IsNullOrEmpty(info.Value.miGetString("MuxingMode")) ? string.Empty : string.Format("<tr><td>Muxing mode:</td><td>{0}</td></tr>", info.Value.miGetString("MuxingMode"))); lines.Add(string.IsNullOrEmpty(info.Value.miGetString("CodecID/String")) ? string.Empty : string.Format("<tr><td>Codec ID:</td><td>{0}</td></tr>", info.Value.miGetString("CodecID/String"))); lines.Add(string.IsNullOrEmpty(info.Value.miGetString("Duration/String")) ? string.Empty : string.Format("<tr><td>Duration:</td><td>{0}</td></tr>", info.Value.miGetString("Duration/String"))); lines.Add(string.IsNullOrEmpty(info.Value.miGetString("BitRate/String")) ? string.Empty : string.Format("<tr><td>Bitrate:</td><td>{0}</td></tr>", info.Value.miGetString("BitRate/String"))); lines.Add(string.IsNullOrEmpty(info.Value.miGetString("BitRate_Nominal/String")) ? string.Empty : string.Format("<tr><td>Nominal bitrate:</td><td>{0}</td></tr>", info.Value.miGetString("BitRate_Nominal/String"))); lines.Add(string.IsNullOrEmpty(info.Value.miGetString("Width/String")) ? string.Empty : string.Format("<tr><td>Width:</td><td>{0}</td></tr>", info.Value.miGetString("Width/String"))); lines.Add(string.IsNullOrEmpty(info.Value.miGetString("Height/String")) ? string.Empty : string.Format("<tr><td>Height:</td><td>{0}</td></tr>", info.Value.miGetString("Height/String"))); lines.Add(string.IsNullOrEmpty(info.Value.miGetString("DisplayAspectRatio/String")) ? string.Empty : string.Format("<tr><td>Display aspect ratio:</td><td>{0}</td></tr>", info.Value.miGetString("DisplayAspectRatio/String"))); lines.Add(string.IsNullOrEmpty(info.Value.miGetString("FrameRate_Mode/String")) ? string.Empty : string.Format("<tr><td>Frame rate mode:</td><td>{0}</td></tr>", info.Value.miGetString("FrameRate_Mode/String"))); lines.Add(string.IsNullOrEmpty(info.Value.miGetString("FrameRate/String")) ? string.Empty : string.Format("<tr><td>Frame rate:</td><td>{0}</td></tr>", info.Value.miGetString("FrameRate/String"))); lines.Add(string.IsNullOrEmpty(info.Value.miGetString("ColorSpace")) ? string.Empty : string.Format("<tr><td>Color space:</td><td>{0}</td></tr>", info.Value.miGetString("ColorSpace"))); lines.Add(string.IsNullOrEmpty(info.Value.miGetString("ChromaSubsampling")) ? string.Empty : string.Format("<tr><td>Chroma subsampling:</td><td>{0}</td></tr>", info.Value.miGetString("ChromaSubsampling"))); lines.Add(string.IsNullOrEmpty(info.Value.miGetString("BitDepth/String")) ? string.Empty : string.Format("<tr><td>Bit depth:</td><td>{0}</td></tr>", info.Value.miGetString("BitDepth/String"))); lines.Add(string.IsNullOrEmpty(info.Value.miGetString("ScanType")) ? string.Empty : string.Format("<tr><td>Scan type:</td><td>{0}</td></tr>", info.Value.miGetString("ScanType"))); lines.Add(string.IsNullOrEmpty(info.Value.miGetString("Bits-(Pixel*Frame)")) ? string.Empty : string.Format("<tr><td>Bits/(Pixel*Frame):</td><td>{0}</td></tr>", info.Value.miGetString("Bits-(Pixel*Frame)"))); lines.Add(string.IsNullOrEmpty(info.Value.miGetString("StreamSize/String")) ? string.Empty : string.Format("<tr><td>Stream size:</td><td>{0}</td></tr>", info.Value.miGetString("StreamSize/String"))); lines.Add(string.IsNullOrEmpty(info.Value.miGetString("Encoded_Library/String")) ? string.Empty : string.Format("<tr><td>Writing library:</td><td>{0}</td></tr>", info.Value.miGetString("Encoded_Library/String"))); lines.Add(string.IsNullOrEmpty(info.Value.miGetString("Encoded_Library_Settings")) ? string.Empty : string.Format("<tr><td>Encoding settings:</td><td>{0}</td></tr>", info.Value.miGetString("Encoded_Library_Settings"))); lines.Add(string.IsNullOrEmpty(info.Value.miGetString("Language/String")) ? string.Empty : string.Format("<tr><td>Language:</td><td>{0}</td></tr>", info.Value.miGetString("Language/String"))); lines.Add(string.IsNullOrEmpty(info.Value.miGetString("Default/String")) ? string.Empty : string.Format("<tr><td>Default:</td><td>{0}</td></tr>", info.Value.miGetString("Default/String"))); lines.Add(string.IsNullOrEmpty(info.Value.miGetString("Forced/String")) ? string.Empty : string.Format("<tr><td>Forced:</td><td>{0}</td></tr>", info.Value.miGetString("Forced/String"))); lines.Add(string.IsNullOrEmpty(info.Value.miGetString("colour_range")) ? string.Empty : string.Format("<tr><td>Color range:</td><td>{0}</td></tr>", info.Value.miGetString("colour_range"))); lines.Add(string.IsNullOrEmpty(info.Value.miGetString("colour_primaries")) ? string.Empty : string.Format("<tr><td>Color primaries:</td><td>{0}</td></tr>", info.Value.miGetString("colour_primaries"))); lines.Add(string.IsNullOrEmpty(info.Value.miGetString("transfer_characteristics")) ? string.Empty : string.Format("<tr><td>Transfer characteristics:</td><td>{0}</td></tr>", info.Value.miGetString("transfer_characteristics"))); lines.Add(string.IsNullOrEmpty(info.Value.miGetString("matrix_coefficients")) ? string.Empty : string.Format("<tr><td>Matrix coefficients:</td><td>{0}</td></tr>", info.Value.miGetString("matrix_coefficients"))); } if (mediaFile.Audio.Count > 0) { int audioTracks = 1; foreach (var info in mediaFile.Audio) { lines.Add(mediaFile.Audio.Count == 1 ? "<tr><td class='thead' colspan='2'><b>Audio</b></td></tr>" : string.Format("<tr><td class='thead' colspan='2'><b>Audio #{0}</b></td></tr>", audioTracks)); lines.Add(string.Format("<tr><td>ID:</td><td>{0}</td></tr>", info.Value.miGetString("ID/String"))); lines.Add(string.IsNullOrEmpty(info.Value.miGetString("Title")) ? string.Empty : string.Format("<tr><td>Title:</td><td>{0}</td></tr>", info.Value.miGetString("Title"))); lines.Add(string.IsNullOrEmpty(info.Value.miGetString("Format")) ? string.Empty : string.Format("<tr><td>Format:</td><td>{0}</td></tr>", info.Value.miGetString("Format"))); lines.Add(string.IsNullOrEmpty(info.Value.miGetString("Format/Info")) ? string.Empty : string.Format("<tr><td>Format info:</td><td>{0}</td></tr>", info.Value.miGetString("Format/Info"))); lines.Add(string.IsNullOrEmpty(info.Value.miGetString("CodecID/String")) ? string.Empty : string.Format("<tr><td>Codec ID:</td><td>{0}</td></tr>", info.Value.miGetString("CodecID/String"))); lines.Add(string.IsNullOrEmpty(info.Value.miGetString("Duration/String")) ? string.Empty : string.Format("<tr><td>Duration:</td><td>{0}</td></tr>", info.Value.miGetString("Duration/String"))); lines.Add(string.IsNullOrEmpty(info.Value.miGetString("BitRate_Mode/String")) ? string.Empty : string.Format("<tr><td>Bitrate mode:</td><td>{0}</td></tr>", info.Value.miGetString("BitRate_Mode/String"))); lines.Add(string.IsNullOrEmpty(info.Value.miGetString("BitRate/String")) ? string.Empty : string.Format("<tr><td>Bitrate:</td><td>{0}</td></tr>", info.Value.miGetString("BitRate/String"))); lines.Add(string.IsNullOrEmpty(info.Value.miGetString("Channel(s)/String")) ? string.Empty : string.Format("<tr><td>Channels:</td><td>{0}</td></tr>", info.Value.miGetString("Channel(s)/String"))); lines.Add(string.IsNullOrEmpty(info.Value.miGetString("SamplingRate/String")) ? string.Empty : string.Format("<tr><td>Sampling rate:</td><td>{0}</td></tr>", info.Value.miGetString("SamplingRate/String"))); lines.Add(string.IsNullOrEmpty(info.Value.miGetString("BitDepth/String")) ? string.Empty : string.Format("<tr><td>Bit depth:</td><td>{0}</td></tr>", info.Value.miGetString("BitDepth/String"))); lines.Add(string.IsNullOrEmpty(info.Value.miGetString("Compression_Mode/String")) ? string.Empty : string.Format("<tr><td>Compression mode:</td><td>{0}</td></tr>", info.Value.miGetString("Compression_Mode/String"))); lines.Add(string.IsNullOrEmpty(info.Value.miGetString("StreamSize/String")) ? string.Empty : string.Format("<tr><td>Stream size:</td><td>{0}</td></tr>", info.Value.miGetString("StreamSize/String"))); lines.Add(string.IsNullOrEmpty(info.Value.miGetString("Language/String")) ? string.Empty : string.Format("<tr><td>Language:</td><td>{0}</td></tr>", info.Value.miGetString("Language/String"))); lines.Add(string.IsNullOrEmpty(info.Value.miGetString("Default/String")) ? string.Empty : string.Format("<tr><td>Default:</td><td>{0}</td></tr>", info.Value.miGetString("Default/String"))); lines.Add(string.IsNullOrEmpty(info.Value.miGetString("Forced/String")) ? string.Empty : string.Format("<tr><td>Forced:</td><td>{0}</td></tr>", info.Value.miGetString("Forced/String"))); audioTracks++; } } if (mediaFile.Text.Count > 0) { int textTracks = 1; foreach (var info in mediaFile.Text) { lines.Add(mediaFile.Text.Count == 1 ? "<tr><td class='thead' colspan='2'><b>Text</b></td></tr>" : string.Format("<tr><td class='thead' colspan='2'><b>Text #{0}</b></td></tr>", textTracks)); lines.Add(string.Format("<tr><td>ID:</td><td>{0}</td></tr>", info.Value.miGetString("ID/String"))); lines.Add(string.IsNullOrEmpty(info.Value.miGetString("Format")) ? string.Empty : string.Format("<tr><td>Format:</td><td>{0}</td></tr>", info.Value.miGetString("Format"))); lines.Add(string.IsNullOrEmpty(info.Value.miGetString("CodecID")) ? string.Empty : string.Format("<tr><td>Codec ID:</td><td>{0}</td></tr>", info.Value.miGetString("CodecID"))); lines.Add(string.IsNullOrEmpty(info.Value.miGetString("CodecID/Info")) ? string.Empty : string.Format("<tr><td>Codec ID info:</td><td>{0}</td></tr>", info.Value.miGetString("CodecID/Info"))); lines.Add(string.IsNullOrEmpty(info.Value.miGetString("Compression_Mode/String")) ? string.Empty : string.Format("<tr><td>Compression mode:</td><td>{0}</td></tr>", info.Value.miGetString("Compression_Mode/String"))); lines.Add(string.IsNullOrEmpty(info.Value.miGetString("Language/String")) ? string.Empty : string.Format("<tr><td>Language:</td><td>{0}</td></tr>", info.Value.miGetString("Language/String"))); lines.Add(string.IsNullOrEmpty(info.Value.miGetString("Default/String")) ? string.Empty : string.Format("<tr><td>Default:</td><td>{0}</td></tr>", info.Value.miGetString("Default/String"))); lines.Add(string.IsNullOrEmpty(info.Value.miGetString("Forced/String")) ? string.Empty : string.Format("<tr><td>Forced:</td><td>{0}</td></tr>", info.Value.miGetString("Forced/String"))); textTracks++; } } if (mediaFile.Menu.Count > 0) { int chapterBegin = int.Parse(mi.Get(StreamKind.Menu, 0, "Chapters_Pos_Begin")); int chapterEnd = int.Parse(mi.Get(StreamKind.Menu, 0, "Chapters_Pos_End")); lines.Add("<tr><td class='thead' colspan='2'><b>Menu</b></td></tr>"); foreach (var info in mediaFile.Menu) { for (int i = chapterBegin; i < chapterEnd; i++) { string key = mi.Get(StreamKind.Menu, 0, i, InfoKind.Name); string value = mi.Get(StreamKind.Menu, 0, i); lines.Add(string.IsNullOrEmpty(info.Value.miGetString(key)) ? string.Empty : string.Format("<tr><td>{0}:</td><td>{1}</td></tr>", key, value)); } } } lines.Add("</table></body></html>"); wb_info.DocumentText = string.Join("\n", lines.ToArray()); }
public async Task <IHttpActionResult> DownloadCourseModuleClip(string clipname, ClipToSave clipToSave) { ClipDownloadData clipUrl = null; // 1- get the video clip url to download. try { clipUrl = GetClipUrl(clipToSave); // 2- make sure the folders structure exist. var videoSaveDirectory = SetUpVideoFolderStructure(clipToSave.CourseTitle, clipToSave.ModuleTitle, clipToSave); // 2b- create course information, if missing SaveCourseInformation(clipToSave); // 3- download the video and report progress back. int receivedBytes = 0; long totalBytes = 0; var videoFileName = ((clipToSave.ClipIndex + 1).ToString("D2") + " - " + clipToSave.Title + ".mp4").ToValidFileName(); var videoSaveLocation = videoSaveDirectory.FullName + "\\raw-" + videoFileName; using (var client = new WebClient()) using (var regStream = await client.OpenReadTaskAsync(clipUrl.URLs[0].URL)) using (var stream = new ThrottledStream(regStream, 115200)) { byte[] buffer = new byte[1024]; totalBytes = Int32.Parse(client.ResponseHeaders[HttpResponseHeader.ContentLength]); stream.MaximumBytesPerSecond = GetClipMaxDownloadSpeed(clipToSave.DurationSeconds, totalBytes); using (var fileStream = File.OpenWrite(videoSaveLocation)) { for (;;) { int bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length); if (bytesRead == 0) { await Task.Yield(); break; } receivedBytes += bytesRead; var progress = new ProgressArgs() { Id = clipToSave.Name, BytesReceived = receivedBytes, FileName = videoFileName, TotalBytes = totalBytes, IsDownloading = true, Extra = new { clipToSave.ModuleIndex, clipToSave.ClipIndex } }; fileStream.Write(buffer, 0, bytesRead); var hubContext = GlobalHost.ConnectionManager.GetHubContext <ProgressHub>(); hubContext.Clients.All.updateProgress(progress); } } } // 4- save the video file. var inputFile = new MediaFile { Filename = videoSaveLocation }; var outputFile = new MediaFile { Filename = videoSaveDirectory.FullName + "\\" + videoFileName }; if (File.Exists(outputFile.Filename)) { File.Delete(outputFile.Filename); } File.Move(inputFile.Filename, outputFile.Filename); // 5- Create srt files if (Constants.SUBTITLES) { var srtFilename = outputFile.Filename.Substring(0, outputFile.Filename.Length - 4) + ".srt"; var srtString = clipToSave.TranscriptClip.GetSrtString(clipToSave.DurationSeconds); if (srtString.Length > 4) { File.WriteAllText(srtFilename, srtString); HandleEmbeddedSubtitles(outputFile.Filename, srtFilename); } } return(Ok(new ProgressArgs() { Id = clipToSave.Name, BytesReceived = receivedBytes, FileName = videoFileName, TotalBytes = totalBytes, IsDownloading = false, Extra = new { clipToSave.ModuleIndex, clipToSave.ClipIndex } })); } catch (Exception exception) { return(HandleException(exception)); } }
internal ConversionProgressEventArgs(ProgressData progressData, MediaFile input, MediaFile output) { Input = input; Output = output; TotalDuration = progressData.TotalDuration; ProcessedDuration = progressData.ProcessedDuration; Frame = progressData.Frame; Fps = progressData.Fps; SizeKb = progressData.SizeKb; Bitrate = progressData.Bitrate; }
internal static Task <MediaPickedEventArgs> GetMediaFileAsync(Context context, int requestCode, string action, bool isPhoto, ref Uri path, Uri data) { Task <Tuple <string, bool> > pathFuture; string originalPath = null; if (action != Intent.ActionPick) { originalPath = path.Path; // Not all camera apps respect EXTRA_OUTPUT, some will instead // return a content or file uri from data. if (data != null && data.Path != originalPath) { originalPath = data.ToString(); string currentPath = path.Path; pathFuture = TryMoveFileAsync(context, data, path, isPhoto).ContinueWith(t => new Tuple <string, bool> (t.Result ? currentPath : null, false)); } else { pathFuture = TaskFromResult(new Tuple <string, bool> (path.Path, false)); } } else if (data != null) { originalPath = data.ToString(); path = data; pathFuture = GetFileForUriAsync(context, path, isPhoto); } else { pathFuture = TaskFromResult <Tuple <string, bool> > (null); } return(pathFuture.ContinueWith(t => { string resultPath = t.Result.Item1; if (resultPath != null && File.Exists(t.Result.Item1)) { var mf = new MediaFile(resultPath, () => { return File.OpenRead(resultPath); }, deletePathOnDispose: t.Result.Item2, dispose: (dis) => { if (t.Result.Item2) { try { File.Delete(t.Result.Item1); // We don't really care if this explodes for a normal IO reason. } catch (UnauthorizedAccessException) { } catch (DirectoryNotFoundException) { } catch (IOException) { } } }); return new MediaPickedEventArgs(requestCode, false, mf); } else { return new MediaPickedEventArgs(requestCode, new MediaFileNotFoundException(originalPath)); } })); }
public OIDMedia(MediaFile media) { Media = media; }
public NzbMediaDownload(int id, MediaFile file) { ID = id; mediaFile = file; }
/// <summary> /// Handles result of capture to save image information /// </summary> /// <param name="sender"></param> /// <param name="e">stores information about current captured image</param> private void cameraTask_Completed(object sender, PhotoResult e) { if (e.Error != null) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR)); return; } switch (e.TaskResult) { case TaskResult.OK: try { string fileName = System.IO.Path.GetFileName(e.OriginalFileName); // Save image in media library MediaLibrary library = new MediaLibrary(); Picture image = library.SavePicture(fileName, e.ChosenPhoto); int orient = ImageExifHelper.getImageOrientationFromStream(e.ChosenPhoto); int newAngle = 0; switch (orient) { case ImageExifOrientation.LandscapeLeft: newAngle = 90; break; case ImageExifOrientation.PortraitUpsideDown: newAngle = 180; break; case ImageExifOrientation.LandscapeRight: newAngle = 270; break; case ImageExifOrientation.Portrait: default: break; // 0 default already set } Stream rotImageStream = ImageExifHelper.RotateStream(e.ChosenPhoto, newAngle); // Save image in isolated storage // we should return stream position back after saving stream to media library rotImageStream.Seek(0, SeekOrigin.Begin); byte[] imageBytes = new byte[rotImageStream.Length]; rotImageStream.Read(imageBytes, 0, imageBytes.Length); rotImageStream.Dispose(); string pathLocalStorage = this.SaveImageToLocalStorage(fileName, isoFolder, imageBytes); imageBytes = null; // Get image data MediaFile data = new MediaFile(pathLocalStorage, image); this.files.Add(data); if (files.Count < this.captureImageOptions.Limit) { cameraTask.Show(); } else { DispatchCommandResult(new PluginResult(PluginResult.Status.OK, files)); files.Clear(); } } catch (Exception) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, "Error capturing image.")); } break; case TaskResult.Cancel: if (files.Count > 0) { // User canceled operation, but some images were made DispatchCommandResult(new PluginResult(PluginResult.Status.OK, files)); files.Clear(); } else { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, "Canceled.")); } break; default: if (files.Count > 0) { DispatchCommandResult(new PluginResult(PluginResult.Status.OK, files)); files.Clear(); } else { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, "Did not complete!")); } break; } }
async void OnTakePhotoButtonClicked(object sender, EventArgs e) { await CrossMedia.Current.Initialize(); // Take photo if (CrossMedia.Current.IsCameraAvailable || CrossMedia.Current.IsTakePhotoSupported) { emotionResultLabel.Text = null; photo = await CrossMedia.Current.TakePhotoAsync(new StoreCameraMediaOptions { Name = "emotion.jpg", PhotoSize = PhotoSize.Small }); if (photo != null) { image.Source = ImageSource.FromStream(photo.GetStream); } } else { await DisplayAlert("No Camera", "Camera unavailable.", "OK"); } ((Button)sender).IsEnabled = false; activityIndicator.IsRunning = true; // Recognize emotion try { if (photo != null) { var faceAttributes = new FaceAttributeType[] { FaceAttributeType.Emotion }; var photoStream = photo.GetStream(); try { Face[] faces = await _faceRecognitionService.DetectAsync(photoStream, true, false, faceAttributes); while (!faces.Any()) { faces = await _faceRecognitionService.DetectAsync(photoStream, true, false, faceAttributes); emotionResultLabel.Text = faces.FirstOrDefault().FaceAttributes.Emotion.ToRankedList().FirstOrDefault().Key; } emotionResultLabel.Text = faces.FirstOrDefault().FaceAttributes.Emotion.ToRankedList().FirstOrDefault().Key; if (faces.Any()) { emotionResultLabel.Text = faces.FirstOrDefault().FaceAttributes.Emotion.ToRankedList().FirstOrDefault().Key; } photo.Dispose(); } catch (Exception ex) { Debug.WriteLine(ex.Message); } //using (var photoStream = photo.GetStream()) //{ // Face[] faces = await _faceRecognitionService.DetectAsync(photoStream, true, false, faceAttributes); // await DisplayAlert("Photo using", "Début de traitement de votre photo.", "OK"); // if (faces.Any()) // { // await DisplayAlert("faces Any", "test.", "OK"); // // Emotions detected are happiness, sadness, surprise, anger, fear, contempt, disgust, or neutral. // emotionResultLabel.Text = faces.FirstOrDefault().FaceAttributes.Emotion.ToRankedList().FirstOrDefault().Key; // } // if (emotionResultLabel.Text == null) // { // await DisplayAlert("No Photo", "Désolé on n'a pas pu traiter votre photo.", "OK"); // emotionResultLabel.Text = "Désolé on n'a pas pu traiter votre photo"; // } // photo.Dispose(); //} } if (emotionResultLabel.Text == null) { emotionResultLabel.Text = "Désolé on n'a pas pu traiter votre photo"; } } catch (FaceAPIException fx) { Debug.WriteLine(fx.Message); } catch (Exception ex) { Debug.WriteLine(ex.Message); } activityIndicator.IsRunning = false; ((Button)sender).IsEnabled = true; }
public Level11(string email, int stud, int num, int score, double totaltime) { Email = email; id = stud; InitializeComponent(); TotalTime = totaltime; Score = score; InitializeComponent(); Num = num; clicked = 0; Starttime = DateTime.Now.ToLocalTime(); NavigationPage.SetHasNavigationBar(this, false); games[0] = new Game() { Pic1 = "https://s3.amazonaws.com/cloudgamingmulitmediabucket/visual+/wall.png", Pic2 = "https://s3.amazonaws.com/cloudgamingmulitmediabucket/visual+/icecream.png", Pic3 = "https://s3.amazonaws.com/cloudgamingmulitmediabucket/visual+/Knife.png", Pic4 = "https://s3.amazonaws.com/cloudgamingmulitmediabucket/visual+/hotdrink.png", sound = "https://s3.amazonaws.com/cloudgamingmulitmediabucket/audio/last+virsion/wall.opus", Text = "ماهو الشي ذو الملمس الخشن" }; games[1] = new Game() { Pic1 = "https://s3.amazonaws.com/cloudgamingmulitmediabucket/visual+/wall.png", Pic2 = "https://s3.amazonaws.com/cloudgamingmulitmediabucket/visual+/icecream.png", Pic3 = "https://s3.amazonaws.com/cloudgamingmulitmediabucket/visual+/Knife.png", Pic4 = "https://s3.amazonaws.com/cloudgamingmulitmediabucket/visual+/hotdrink.png", sound = "https://s3.amazonaws.com/cloudgamingmulitmediabucket/audio/last+virsion/knife.opus", Text = "ماهو الشي ذو الملمس الحاد" }; games[2] = new Game() { Pic1 = "https://s3.amazonaws.com/cloudgamingmulitmediabucket/visual+/wall.png", Pic2 = "https://s3.amazonaws.com/cloudgamingmulitmediabucket/visual+/icecream.png", Pic3 = "https://s3.amazonaws.com/cloudgamingmulitmediabucket/visual+/Knife.png", Pic4 = "https://s3.amazonaws.com/cloudgamingmulitmediabucket/visual+/hotdrink.png", sound = "https://s3.amazonaws.com/cloudgamingmulitmediabucket/audio/last+virsion/coffee.opus", Text = "ماهو الشي ذو الملمس الحار" }; games[3] = new Game() { Pic1 = "https://s3.amazonaws.com/cloudgamingmulitmediabucket/visual+/wall.png", Pic2 = "https://s3.amazonaws.com/cloudgamingmulitmediabucket/visual+/icecream.png", Pic3 = "https://s3.amazonaws.com/cloudgamingmulitmediabucket/visual+/Knife.png", Pic4 = "https://s3.amazonaws.com/cloudgamingmulitmediabucket/visual+/hotdrink.png", sound = "https://s3.amazonaws.com/cloudgamingmulitmediabucket/audio/last+virsion/icecream.opus", Text = "ماهو الشي ذو الملمس البارد" }; // https://s3.ap-south-1.amazonaws.com/cloudgamingapp/Blue+face.png pic1.Source = games[num].Pic1; pic2.Source = games[num].Pic2; pic3.Source = games[num].Pic3; pic4.Source = games[num].Pic4; question.Text = games[num].Text; switch (Num) { case 0: theRightAnswer = "https://s3.amazonaws.com/cloudgamingmulitmediabucket/visual+/wall.png"; break; case 1: theRightAnswer = "https://s3.amazonaws.com/cloudgamingmulitmediabucket/visual+/Knife.png"; break; case 2: theRightAnswer = "https://s3.amazonaws.com/cloudgamingmulitmediabucket/visual+/hotdrink.png"; break; case 3: theRightAnswer = "https://s3.amazonaws.com/cloudgamingmulitmediabucket/visual+/icecream.png"; break; } file = new MediaFile(games[Num].sound); CrossMediaManager.Current.Play(file); CrossMediaManager.Current.MediaFinished += Current_MediaFinished; question.GestureRecognizers.Add( new TapGestureRecognizer() { Command = new Command(() => { CrossMediaManager.Current.Play(file); CrossMediaManager.Current.MediaFinished += Current_MediaFinished; }) }); }
public IRemuxer GetRemuxer(MediaFile inputFile, string outputFile, VideoMuxerType muxer) { return(registry.Retrieve <IRemuxer> (InstanceType.New, inputFile.FilePath, outputFile, muxer)); }
public async override void Init(object initData) { base.Init(initData); if (initData is SeancesModel) { IsLoading = true; SeanceModel = ((SeancesModel)initData); this.PageWasPopped += Handle_PageWasPopped; App.ApplicationIsPaused += App_ApplicationIsPaused; Tint = Color.FromHex(SeanceModel.Tint.Substring(1)); TintDark = ((Tint).AddLuminosity(-0.2)); Title = Settings.DeviceLanguage == "English" ? SeanceModel.Meditation.Label_EN : SeanceModel.Meditation.Label; MeditationFile meditationFile = GetMeditationFileForUser(SeanceModel.Meditation, SeanceModel.Level); if (meditationFile == null) { IsLoading = false; return; } AudioPlayer.PlayingChanged += AudioPlayer_PlayingChanged; AudioPlayer.MediaFailed += AudioPlayer_MediaFailed; AudioPlayer.MediaFinished += AudioPlayer_MediaFinished; AudioPlayer.StatusChanged += AudioPlayer_StatusChanged; var url = Constants.RestUrl + "file/" + meditationFile.Path; if (SeanceModel.IsDownloaded) { var data = await StoreManager.MeditationStore.IsAvailableOffline(SeanceModel.Meditation.Id + SeanceModel.Level + Settings.Voice + Settings.Language); if (data != null && data.Item1 && data.Item2 != null) { var pathToFileURL = new System.Uri(data.Item2).AbsolutePath; if (Device.RuntimePlatform == Device.Android) { Device.BeginInvokeOnMainThread(async() => { await AudioPlayer.Play(file = new MediaFile(pathToFileURL, Plugin.MediaManager.Abstractions.Enums.MediaFileType.Audio, ResourceAvailability.Local)); }); } else { Device.BeginInvokeOnMainThread(async() => { await AudioPlayer.Play(file = new MediaFile("file://" + pathToFileURL)); }); } } else { Device.BeginInvokeOnMainThread(async() => { await AudioPlayer.Play(file = new MediaFile(url, Plugin.MediaManager.Abstractions.Enums.MediaFileType.Audio, Plugin.MediaManager.Abstractions.Enums.ResourceAvailability.Remote)); }); } } else { Device.BeginInvokeOnMainThread(async() => { await AudioPlayer.Play(file = new MediaFile(url, Plugin.MediaManager.Abstractions.Enums.MediaFileType.Audio, Plugin.MediaManager.Abstractions.Enums.ResourceAvailability.Remote)); }); } } }
public async void SubmitButton_Clicked(object sender, System.EventArgs e) { if (IsLoading) { return; } IsLoading = true; if (string.IsNullOrEmpty(Email)) { DependencyService.Get <IDialogService>().ShowAlert(null, "You must enter an email to add the user."); IsLoading = false; return; } else if (!Email.Contains("@") || !Email.Contains(".com")) { //Improperly Formatted Email DependencyService.Get <IDialogService>().ShowAlert(null, "Email is not properly formatted."); IsLoading = false; return; } //Acceptable Email if (file == null) { //No Image taken so far DependencyService.Get <IDialogService>().ShowAlert(null, "You must take a picture first!"); IsLoading = false; return; } using (var fileStream = file.GetStream()) { var fileBytes = fileStream.ReadToEnd(); var uploadResponse = await IdentityService.Instance.UploadIdentity(Email, fileBytes); System.Diagnostics.Debug.WriteLine(uploadResponse); if (uploadResponse.Contains("Saved")) { DependencyService.Get <IDialogService>().ShowAlert(null, new IdentityResponse(Enums.IdentityType.Success, $"Saved {Email} successfully and trained model.")); } else if (uploadResponse.Contains("Glasses")) { DependencyService.Get <IDialogService>().ShowAlert(null, new IdentityResponse(Enums.IdentityType.Glasses, uploadResponse)); } else if (uploadResponse.Contains("No face detected")) { DependencyService.Get <IDialogService>().ShowAlert(null, new IdentityResponse(Enums.IdentityType.NoFacesDetected, uploadResponse)); } else { DependencyService.Get <IDialogService>().ShowAlert(null, uploadResponse); } } file = null; IsLoading = false; OnPropertyChanged("ProfilePicSource"); }
public override bool BuildFrame(MediaFile file, MediaFrame mediaFrame, Stream buffer) { buffer.WriteByte(0x2f); return(base.BuildFrame(file, mediaFrame, buffer)); }
public async void Submit_Data(object sender, EventArgs e) { // Check Connectivity var conect = Connectivity.NetworkAccess; if (conect == NetworkAccess.Internet) { //Validate the from if (entDescription.Text == null) { // errorDescription.IsVisible = true; } else { // errorType.IsVisible = false; // errorDescription.IsVisible = false; forname = Guid.NewGuid().ToString(); if (_received == null) { await DisplayAlert("Error!", "There is an Error with the Image, Please Capture", "Close"); } else { // UploadImage(_received.GetStream()); if (chkAgree.IsChecked == false) { await DisplayAlert("Submission Error", "Please Argree to the Information Provided by checking the box above", "Close"); } else { //Create Variables to Capture string received_Lat = lat.ToString(); string received_Lng = lon.ToString(); string received_Date = DateTime.Now.ToString(); reporter ic = new reporter() { ReporterFullname = entReporterName.Text.ToString(), ReporterPhoneNo = entPhoneNumber.Text.ToString(), Category = lblReportType.Text.ToString(), Description = entDescription.Text.ToString(), CategorySubType = PickType.SelectedItem.ToString(), LongX = received_Lng, LatY = received_Lat, CapturedImage = "gs://eedcmobileapp.appspot.com/incidence/" + forname + ".png", CapturedIssueDate = received_Date }; await PopupNavigation.Instance.PushAsync(new loading()); // Serialize the Model object and Post the data var jsonObject = JsonConvert.SerializeObject(ic); var context = new StringContent(jsonObject, Encoding.UTF8, "application/json"); try { HttpClient hc = new HttpClient(); var result = await hc.PostAsync("https://denceapp.somee.com/api/Incidence/reportIncident/", context); var code = result.StatusCode; if (result.StatusCode == HttpStatusCode.OK) { await dbfire.saveImage(_received.GetStream(), forname); //Get the Track ID for the user to show on successful submission panel List <incidenceApp> trackData = new List <incidenceApp>(); using (var client = new HttpClient()) { client.BaseAddress = new Uri("https://denceapp.somee.com/api/incidence/getTrackID/"); var responseTask = client.GetAsync(forname); responseTask.Wait(); var res = responseTask.Result; if (res.IsSuccessStatusCode) { string readTask = await res.Content.ReadAsStringAsync(); trackData = JsonConvert.DeserializeObject <List <incidenceApp> >(readTask); foreach (var dataReterived in trackData) { userTrackID = dataReterived.incidenceId.ToString().ToUpper(); } } } ClearFieldsData(); await PopupNavigation.Instance.PopAsync(); PickType.SelectedIndex = 0; MessagingCenter.Send <Object, String>(this, "Tracker", userTrackID); await PopupNavigation.Instance.PushAsync(new Success(userTrackID)); _received = null; } else { //Internal Server Error await DisplayAlert("Server Error!", "There was an Error Conecting to the server, Please Ensure you are connected to the internet and try again!", "Close"); await PopupNavigation.Instance.PushAsync(new network()); } } catch (Exception ex) { await DisplayAlert("Message!!", ex.Message, "Close"); } } } } } else { await PopupNavigation.Instance.PushAsync(new network()); } }
private string GetFileImageUrl(MediaFile image, Size targetSize) { return(GetUrl(image.Size, targetSize, () => _fileService.GetFileLocation(image, targetSize)) ?? image.FileUrl); }
protected virtual int ProcessPictures(ImportExecuteContext context, IEnumerable <ImportRow <Category> > batch) { var allFileIds = batch .Where(row => row.HasDataValue("ImageUrl") && row.Entity.MediaFileId > 0) .Select(row => row.Entity.MediaFileId.Value) .Distinct() .ToArray(); var allFiles = _mediaService.GetFilesByIds(allFileIds).ToDictionary(x => x.Id, x => x.File); var catalogAlbumId = _folderService.GetNodeByPath(SystemAlbumProvider.Catalog).Value.Id; foreach (var row in batch) { try { var imageUrl = row.GetDataValue <string>("ImageUrl"); if (imageUrl.IsEmpty()) { continue; } var image = CreateDownloadImage(context, imageUrl, 1); if (image == null) { continue; } if (image.Url.HasValue() && !image.Success.HasValue) { AsyncRunner.RunSync(() => _fileDownloadManager.DownloadAsync(DownloaderContext, new FileDownloadManagerItem[] { image })); } if ((image.Success ?? false) && File.Exists(image.Path)) { Succeeded(image); using (var stream = File.OpenRead(image.Path)) { if ((stream?.Length ?? 0) > 0) { var assignedFile = allFiles.Get(row.Entity.MediaFileId ?? 0); MediaFile sourceFile = null; if (assignedFile != null && _mediaService.FindEqualFile(stream, new[] { assignedFile }, true, out var _)) { context.Result.AddInfo($"Found equal image in data store for '{image.FileName}'. Skipping file.", row.GetRowInfo(), "ImageUrl"); } else if (_mediaService.FindEqualFile(stream, image.FileName, catalogAlbumId, true, out sourceFile)) { context.Result.AddInfo($"Found equal image in catalog album for '{image.FileName}'. Assigning existing file instead.", row.GetRowInfo(), "ImageUrl"); } else { var path = _mediaService.CombinePaths(SystemAlbumProvider.Catalog, image.FileName); sourceFile = _mediaService.SaveFile(path, stream, false, DuplicateFileHandling.Rename)?.File; } if (sourceFile?.Id > 0) { row.Entity.MediaFileId = sourceFile.Id; _categoryRepository.Update(row.Entity); } } } } else if (image.Url.HasValue()) { context.Result.AddInfo("Download of an image failed.", row.GetRowInfo(), "ImageUrls"); } } catch (Exception ex) { context.Result.AddWarning(ex.ToAllMessages(), row.GetRowInfo(), "ImageUrls"); } } var num = _categoryRepository.Context.SaveChanges(); return(num); }
/// <summary> /// 临时媒体文件上传(有效期3天) /// <para>用于上传图片、语音、视频等媒体资源文件以及普通文件(如doc,ppt)</para> /// </summary> /// <param name="filePath">文件绝对路径</param> /// <param name="fileType">文件类型</param> /// <returns>上传结果</returns> public static MediaFile.UploadTempReturnValue UploadTempFile(string filePath, MediaFile.FileType fileType) { if (!File.Exists(filePath)) { return(new MediaFile.UploadTempReturnValue(-1, "文件 " + filePath + " 不存在")); } string url = string.Format("{0}?access_token={1}&type={2}", ServiceUrl.UploadMediaFile_Temp, AccessToken.Value, MediaFile.GetFileTypeString(fileType)); return(JsonConvert.DeserializeObject <MediaFile.UploadTempReturnValue>(UploadFile(url, filePath))); }
bool CreateProject() { TreeIter iter; MediaFile file; if (projectType == ProjectType.FileProject || projectType == ProjectType.EditProject) { if (!mediafilesetselection1.FileSet.CheckFiles()) { dialogs.WarningMessage(Catalog.GetString("You need at least 1 video file for the main angle")); return(false); } } if (project != null) { FillProject(); return(true); } if (projectType == ProjectType.CaptureProject || projectType == ProjectType.URICaptureProject) { if (String.IsNullOrEmpty(capturemediafilechooser.CurrentPath)) { dialogs.WarningMessage(Catalog.GetString("No output video file")); return(false); } } if (projectType == ProjectType.URICaptureProject) { if (urientry.Text == "") { dialogs.WarningMessage(Catalog.GetString("No input URI")); return(false); } } project = new LMProject(); project.Description = new ProjectDescription(); FillProject(); encSettings = new EncodingSettings(); captureSettings = new CaptureSettings(); encSettings.OutputFile = capturemediafilechooser.CurrentPath; /* Get quality info */ qualitycombobox.GetActiveIter(out iter); encSettings.EncodingQuality = (EncodingQuality)qualList.GetValue(iter, 1); /* Get size info */ imagecombobox.GetActiveIter(out iter); encSettings.VideoStandard = (VideoStandard)videoStandardList.GetValue(iter, 1); /* Get encoding profile info */ encodingcombobox.GetActiveIter(out iter); encSettings.EncodingProfile = (EncodingProfile)encProfileList.GetValue(iter, 1); encSettings.Framerate_n = App.Current.Config.FPS_N; encSettings.Framerate_d = App.Current.Config.FPS_D; captureSettings.EncodingSettings = encSettings; file = project.Description.FileSet.FirstOrDefault(); if (file == null) { file = new MediaFile() { Name = Catalog.GetString("Main camera angle") }; file.FilePath = capturemediafilechooser.CurrentPath; file.Fps = (ushort)(App.Current.Config.FPS_N / App.Current.Config.FPS_D); file.Par = 1; project.Description.FileSet.Add(file); } if (projectType == ProjectType.CaptureProject) { captureSettings.Device = videoDevices [devicecombobox.Active]; captureSettings.Format = captureSettings.Device.Formats [deviceformatcombobox.Active]; file.VideoHeight = encSettings.VideoStandard.Height; file.VideoWidth = encSettings.VideoStandard.Width; } else if (projectType == ProjectType.URICaptureProject) { string uri = urientry.Text; if (!String.IsNullOrEmpty(userentry.Text) || !String.IsNullOrEmpty(passwordentry.Text)) { int index = uri.IndexOf("://", StringComparison.Ordinal); if (index != -1) { uri = uri.Insert(index + 3, string.Format("{0}:{1}@", userentry.Text, passwordentry.Text)); } } captureSettings.Device = new Device { DeviceType = CaptureSourceType.URI, ID = uri }; file.VideoHeight = encSettings.VideoStandard.Height; file.VideoWidth = encSettings.VideoStandard.Width; } else if (projectType == ProjectType.FakeCaptureProject) { file.FilePath = Constants.FAKE_PROJECT; } return(true); }
/// <summary> /// 永久媒体文件上传 /// <para>用于上传图片、语音、视频等媒体资源文件以及普通文件(如doc,ppt)</para> /// </summary> /// <param name="filePath">文件绝对路径</param> /// <param name="fileType">文件类型</param> /// <param name="appId">应用ID</param> /// <returns>上传结果</returns> public static MediaFile.UploadForeverReturnValue UploadForeverFile(string filePath, MediaFile.FileType fileType, int appId) { if (!File.Exists(filePath)) { return(new MediaFile.UploadForeverReturnValue(-1, "文件 " + filePath + " 不存在")); } string url = string.Format("{0}?agentid={1}&type={2}&access_token={3}", ServiceUrl.UploadMediaFile_Forever, appId, MediaFile.GetFileTypeString(fileType), AccessToken.Value); return(JsonConvert.DeserializeObject <MediaFile.UploadForeverReturnValue>(UploadFile(url, filePath))); }
public MediaTool(string filePath) { this.mediaFile = new MediaFile(filePath); }
private static string Convert(MediaFile inputFile, MediaFile outputFile, ConversionOptions conversionOptions) { var commandBuilder = new StringBuilder(); // Default conversion if (conversionOptions == null) { return(commandBuilder.AppendFormat(" -i \"{0}\" \"{1}\" ", inputFile.Filename, outputFile.Filename).ToString()); } // Media seek position if (conversionOptions.Seek != null) { commandBuilder.AppendFormat(CultureInfo.InvariantCulture, " -ss {0} ", conversionOptions.Seek.Value.TotalSeconds); } commandBuilder.AppendFormat(" -i \"{0}\" ", inputFile.Filename); // Physical media conversion (DVD etc) if (conversionOptions.Target != Target.Default) { commandBuilder.Append(" -target "); if (conversionOptions.TargetStandard != TargetStandard.Default) { commandBuilder.AppendFormat(" {0}-{1} \"{2}\" ", conversionOptions.TargetStandard.ToLower(), conversionOptions.Target.ToLower(), outputFile.Filename); return(commandBuilder.ToString()); } commandBuilder.AppendFormat("{0} \"{1}\" ", conversionOptions.Target.ToLower(), outputFile.Filename); return(commandBuilder.ToString()); } // Audio sample rate if (conversionOptions.AudioSampleRate != AudioSampleRate.Default) { commandBuilder.AppendFormat(" -ar {0} ", conversionOptions.AudioSampleRate.Remove("Hz")); } // Maximum video duration if (conversionOptions.MaxVideoDuration != null) { commandBuilder.AppendFormat(" -t {0} ", conversionOptions.MaxVideoDuration); } // Video bit rate if (conversionOptions.VideoBitRate != null) { commandBuilder.AppendFormat(" -b {0}k ", conversionOptions.VideoBitRate); } // Video frame rate if (conversionOptions.VideoFps != null) { commandBuilder.AppendFormat(" -r {0} ", conversionOptions.VideoFps); } // Video size / resolution if (conversionOptions.VideoSize == VideoSize.Custom) { commandBuilder.AppendFormat(" -vf \"scale={0}:{1}\" ", conversionOptions.CustomWidth ?? -2, conversionOptions.CustomHeight ?? -2); } else if (conversionOptions.VideoSize != VideoSize.Default) { string size = conversionOptions.VideoSize.ToLower(); if (size.StartsWith("_")) { size = size.Replace("_", ""); } if (size.Contains("_")) { size = size.Replace("_", "-"); } commandBuilder.AppendFormat(" -s {0} ", size); } // Video aspect ratio if (conversionOptions.VideoAspectRatio != VideoAspectRatio.Default) { string ratio = conversionOptions.VideoAspectRatio.ToString(); ratio = ratio.Substring(1); ratio = ratio.Replace("_", ":"); commandBuilder.AppendFormat(" -aspect {0} ", ratio); } // Video cropping if (conversionOptions.SourceCrop != null) { var crop = conversionOptions.SourceCrop; commandBuilder.AppendFormat(" -filter:v \"crop={0}:{1}:{2}:{3}\" ", crop.Width, crop.Height, crop.X, crop.Y); } if (conversionOptions.BaselineProfile) { commandBuilder.Append(" -profile:v baseline "); } return(commandBuilder.AppendFormat(" \"{0}\" ", outputFile.Filename).ToString()); }
public MediaTool() { this.mediaFile = new MediaFile(""); }
public static void SaveImageTag(MediaFile image, IEnumerable <ImageTag> tags) { imageTagEntities.Add(new ImageTagEntity { Image = image, Tags = tags }); }
public IEnumerable<MediaSegment> Segment(FileInfo file, long fileId) { var source = new MediaFile(file.FullName); using (var engine = new Engine()) { engine.GetMetadata(source); var progressMs = 0.0; while (progressMs < source.Metadata.Duration.TotalMilliseconds) { var options = new ConversionOptions(); var endMs = Math.Min(progressMs + _segmentLengthMs, source.Metadata.Duration.TotalMilliseconds); options.CutMedia(TimeSpan.FromMilliseconds(progressMs), TimeSpan.FromMilliseconds(endMs)); var outputFile = Path.Combine(file.DirectoryName, string.Format("{0}_audio_{1}ms.wav", file.Name, progressMs)); engine.Convert(source, new MediaFile(outputFile), options); yield return new MediaSegment { FileId = fileId, File = new FileInfo(outputFile), OffsetMs = progressMs, DurationMs = endMs - progressMs }; progressMs = endMs; } } }