private async Task AddFiles(string[] files, VideoFile before = null, int groupIndex = -1) { var infoBox = InfoBox.Show(this, Properties.Resources.ReadingFile); try { await Data.AddFiles(files, before, groupIndex); } catch (Exception ex) { MessageBox.Show(ex.Message, "File format error"); } finally { infoBox.Close(); } }
public async Task <IHttpActionResult> DeleteVideoFile(Guid id) { VideoFile VideoFile = await db.Videos.FindAsync(id); if (VideoFile == null) { return(NotFound()); } //var client = new VimeoDotNet.VimeoClient("101df01f949f134370f77a375d8e169e7cc43ae8", "9rZXXj+4iRk8Wv95QPNNjf4sU+MI9+O7CczWnRp4L1dQF0V7hGeHA/bR0repqePh+TyvZNnRW2aFlWd34RD5JCfp7clj8nQuFZHRTxYjeSXwutIyJOSW/G9Sv5athNfB"); var client = new VimeoDotNet.VimeoClient("7510a353d5691dd4d17f90455d063329"); await client.DeleteVideoAsync(VideoFile.ClipId); db.Videos.Remove(VideoFile); await db.SaveChangesAsync(); return(Ok(VideoFile)); }
public static void CreateThumbnails(string iFile, string oFile, int time) { VideoFile videoInfo = GetVideoInfo(iFile); oFile = Path.GetFileName(oFile) + "\\" + Path.GetFileName(oFile); iFile = Path.GetFileName(iFile); var num = videoInfo.Duration.TotalSeconds / 2.0; if (num > 8.0) { num = 8.0; } var arguments = string.Format(" -y -i {0} -f image2 -ss {2}.001 -s 240x180 {1}", iFile, oFile, time); var p = CreateProcess(ffmpeg, arguments); RunProcess(p); }
static void CreateThumbnails(string iFile, string oFile, int time) { VideoFile videoInfo = GetVideoInfo(iFile); oFile = ShellPathNameConvert.ToShortPathName(Path.GetDirectoryName(oFile)) + "\\" + Path.GetFileName(oFile); iFile = ShellPathNameConvert.ToShortPathName(iFile); double num = videoInfo.Duration.TotalSeconds / 2.0; if (num > 8.0) { num = 8.0; } string arguments = string.Format(" -y -i {0} -f image2 -ss {2}.001 -s 240x180 {1}", iFile, oFile, time); Process p = CreateProcess(ffmpeg, arguments); RunProcess(p); }
public async Task LoadFromFolder(StorageFolder storageFolder) { IReadOnlyList <StorageFile> fileList = await storageFolder.GetFilesAsync(); const ThumbnailMode thumbnailMode = ThumbnailMode.MusicView; foreach (StorageFile f in fileList) { if (videoFormat.FindIndex(x => x.Equals(f.FileType, StringComparison.OrdinalIgnoreCase)) != -1) { const uint size = 100; using (StorageItemThumbnail thumbnail = await f.GetThumbnailAsync(thumbnailMode, size)) { // Also verify the type is ThumbnailType.Image (album art) instead of ThumbnailType.Icon // (which may be returned as a fallback if the file does not provide album art) if (thumbnail != null && (thumbnail.Type == ThumbnailType.Image || thumbnail.Type == ThumbnailType.Icon)) { BitmapImage bitmapImage = new BitmapImage(); bitmapImage.SetSource(thumbnail); MediaFile o1 = new VideoFile(); VideoProperties videoProperties = await f.Properties.GetVideoPropertiesAsync(); Image i = new Image(); i.Source = bitmapImage; o1.Thumb = i; o1.Title = f.Name; if (videoProperties.Title != "") { o1.Title = videoProperties.Title; } o1.Name = f.Name; o1.Path = f.Path; videoFiles.Add((VideoFile)o1); autoList.Add(o1.Title); } } } } IReadOnlyList <StorageFolder> folderList = await storageFolder.GetFoldersAsync(); foreach (var i in folderList) { await LoadFromFolder(i); } }
protected void btnSave_Click(object sender, EventArgs e) { if (Page.IsValid) { VideoFile video = CurrentVideo; if (video == null) { return; } else { video.VideoTitle = txtVideoTitle.Text; video.CategoryId = Convert.ToInt32(ddlCategory.SelectedValue); video.Order = Convert.ToInt32(rntOrder.Value); video.VideoDescription = txtDescription.Text; if (ddlApproveVideo.SelectedIndex == 1) { video.ApprovementStatus = (short)ApprovedStatus.DaDuyet; } else if (ddlApproveVideo.SelectedIndex == 2) { video.ApprovementStatus = (short)ApprovedStatus.KhongDuyet; } video.ApprovedBy = UserInfo.UserAccount.AccountName; video.ApprovedTime = DateTime.Now; video.ShowInHomepage = ckbShowInHomepage.Checked; VideoApprovementHis his = new VideoApprovementHis(); his.VideoId = video.Id; his.VideoOwner = video.UserAccount.AccountName; his.VideoTitle = video.VideoTitle; his.OriginalFileName = video.OriginalFileName; his.ApprovementDes = txtApprovementDes.Text; his.ApprovementStatus = video.ApprovementStatus; his.ApprovedTime = DateTime.Now; his.ApprovedBy = UserInfo.UserAccount.AccountName; db.VideoApprovementHis.InsertOnSubmit(his); db.SubmitChanges(); Response.Redirect(Common.GenerateAdminUrl("approvevideo")); } } }
public void InscreaseCounter(int iVid) { VideoFile video = db.VideoFiles.SingleOrDefault <VideoFile>(v => v.Id == iVid && v.ApprovementStatus == (short)ApprovedStatus.DaDuyet); if (video != null) { if (video.ViewCount.HasValue) { video.ViewCount++; } else { video.ViewCount = 1; } db.SubmitChanges(); } }
public static bool VerifyTaskLengthAndSplitTask(TASK Task) { int MaxLength; string MaxLengthString = new CONFIG_Service().GetConfigValueById((int)EnumManager.CONFIG.MAXLENGTHWITHOUTSPLIT); int.TryParse(MaxLengthString, out MaxLength); if (Task.LENGTH >= MaxLength) { VideoFile VideoFile = new VideoFile(Task.FILE_URL); VideoFile.GetVideoInfo(); Task.STATUS = 0; new TASK_Service().AddOrUpdateTask(Task); CreateSplits(Task, VideoFile); return(true); } return(false); }
public void Convert(string filename, string format) { var videoFile = new VideoFile(filename); ICodec codec; if (format == "MPEG4") { codec = new Mpeg4Codec(); } else { codec = new OggCodec(); } var videoConverter = new VideoConverter(); videoConverter.Convert(videoFile, codec); }
private static void MainProcess() { try { VideoFile nextfile = _repository.GetNextVideoToEncode(); if (IsFileReady(nextfile)) { _timer.Stop(); log.Info($"Starting encode of file: {nextfile.FullPath}"); StartHandbrake(nextfile); log.Info($"Finished encoding filename: {nextfile.FullPath}"); _timer.Start(); } } catch (Exception ex) { log.Error(ex.Message); } }
private void addFilesToolStripMenuItem_Click(object sender, EventArgs e) { /** ADD A FILE **/ OpenFileDialog diag = new OpenFileDialog(); // TODO: Use autogenerated list diag.Filter = "Video Files|*.mp4;*.avi;*.mov;*.flv;*.mkv"; diag.Title = "Add Files to Library"; diag.Multiselect = true; DialogResult userClickedOk = diag.ShowDialog(); if (userClickedOk == DialogResult.OK) { this.Enabled = false; Cursor.Current = Cursors.WaitCursor; // get the root library path Folder root = Folders.GetFolder(Folders.ROOT_ID); // copy the selected files into the library, and add them to the database foreach (string file in diag.FileNames) { try { string fullPath = root.Name + file.Substring(file.LastIndexOf("\\")); Console.WriteLine(fullPath); File.Copy(file, fullPath); VideoFile fileEntry = new VideoFile( fullPath, MainScreenManager.GetDefaultTags(new FileInfo(fullPath))); Files.AddFile(fileEntry, 1, false); fileEntry = Files.GetFile(Database.GetLastInsertID("files")); Files.AssociateFileLocation(fileEntry, 1); } catch (Exception ex) { Console.WriteLine(ex.ToString()); MessageBox.Show("Error: Unable to copy file " + file + " to library."); } } // refresh the database _mainManager.LibraryManager.RefreshLibraryFromDatabase(); this.Enabled = true; Cursor.Current = Cursors.Default; } }
// associate a file_location relationship with the id of the file's parent folder public static Response AssociateFileLocation(VideoFile file, int parentId) { // locate the video file if it exists string[] rows = { "file_id", "folder_id" }; string[] data = { file.Id.ToString(), parentId.ToString() }; // insert a new file location bool success = Database.SimpleInsertQuery(_fileLocationsTable, rows, data); return((success) ? Response.Success : Response.FailedDatabase); }
public static VideoFile GetVideoInfo(string iFile) { VideoEncoder.Encoder encoder = new VideoEncoder.Encoder(); encoder.FFmpegPath = ffmpeg; VideoFile videoFile = new VideoFile(iFile); encoder.GetVideoInfo(videoFile); TimeSpan duration = videoFile.Duration; StringBuilder stringBuilder = new StringBuilder(); string arg = $"{(int)duration.TotalHours:00}:{duration.Minutes:00}:{duration.Seconds:00}"; stringBuilder.AppendFormat("时间长度:{0}\n", arg); stringBuilder.AppendFormat("高度:{0}\n", videoFile.Height); stringBuilder.AppendFormat("宽度:{0}\n", videoFile.Width); stringBuilder.AppendFormat("数据格式:{0}\n", videoFile.VideoFormat); stringBuilder.AppendFormat("比特率:{0}\n", videoFile.BitRate); stringBuilder.AppendFormat("文件路径:{0}\n", videoFile.File); return(videoFile); }
public DuplicateWrapper( VideoFile file1, VideoFile file2, string basePath) { _ = file1.FileSize; _ = file1.Duration; _ = file1.CodecInfo; _ = file2.FileSize; _ = file2.Duration; _ = file2.CodecInfo; DuplicateData = new DuplicateData { DuplicateId = Guid.NewGuid(), File1 = file1, File2 = file2, BasePath = basePath, }; }
public IActionResult Upload() { if (HttpContext.Request.Form.Files[0] != null) { var file = HttpContext.Request.Form.Files[0]; using (MemoryStream ms = new MemoryStream()) { file.CopyTo(ms); VideoFile _video = new VideoFile(); _video.ContentType = file.ContentType; _video.FileName = file.FileName; _video.data = ms.ToArray(); _context.VideoFile.Add(_video); _context.SaveChanges(); } } return(Redirect("~/")); }
public static bool FFmpegMergeSplits(TASK Task, List <TASK> ListSubTasks) { try { // On récupère la liste des urls d'acces des sous taches pour reassemblage List <string> listOfUrls = new List <string>(); foreach (var item in ListSubTasks) { listOfUrls.Add(item.FILE_URL_DESTINATION); } // On va former l'url de destination du fichier de base string fileUrl = Task.FILE_URL_TEMP; int count = (fileUrl.LastIndexOf(@"\") + 1); string fileName = fileName = fileUrl.Substring(count); count = (fileName.LastIndexOf('.') + 1); fileName = fileName.Substring(0, count); Task.FILE_URL_DESTINATION = destinationFolder + @"\" + fileName + new FORMAT_Service().GetFormatById((int)Task.FK_ID_FORMAT_TO_CONVERT).FORMAT_NAME; // On merge les splits VideoFile.MergeVideoWithSplits(listOfUrls, Task.FILE_URL_DESTINATION); return(true); } catch (Exception e) { Task.STATUS = (int)EnumManager.PARAM_TASK_STATUS.ERREUR; new TASK_Service().UpdateTask(Task); TRACE trace = new TRACE() { FK_ID_TASK = Task.PK_ID_TASK, FK_ID_SERVER = 1, DATE_TRACE = DateTime.Now, NOM_SERVER = System.Environment.MachineName, METHOD = "FFMPEG Merge Split", TYPE = "ERROR", DESCRIPTION = e.Message + " " + e.InnerException }; new TRACE_Service().AddTrace(trace); return(false); } }
public static void CreateSplits(TASK MotherTask, VideoFile VideoFile) { // On récupère le nombre de split a effectuer int Splits = GetNumberOfSplits(MotherTask); int SplitsTotal = Splits; // On récupère la longueur de chaque split TimeSpan timeSpan = new TimeSpan(VideoFile.Duration.Ticks / Splits); // On set le debut du premier split TimeSpan begin = new TimeSpan(0); // on récupère la durée totale de la video long durationTotal = VideoFile.Duration.Ticks; // On crée notre param split PARAM_SPLIT paramSplit = new PARAM_SPLIT(); while (Splits != 0) { if (Splits == SplitsTotal) { long stopSpan = new TimeSpan(begin.Ticks + timeSpan.Ticks).Ticks; paramSplit = new PARAM_SPLIT() { BEGIN_PARAM_SPLIT = begin.Ticks.ToString(), END_PARAM_SPLIT = stopSpan.ToString() }; } else { long beginSpan = timeSpan.Ticks * (SplitsTotal - Splits); long stopSpan = (durationTotal / SplitsTotal) + beginSpan; paramSplit = new PARAM_SPLIT() { BEGIN_PARAM_SPLIT = beginSpan.ToString(), END_PARAM_SPLIT = stopSpan.ToString() }; } new PARAM_SPLIT_Service().AddOrUpdateParamSplit(paramSplit); // On crée une sous tache associé au paramSplit et la tache mere CreateSubTask(MotherTask, paramSplit, SplitsTotal); Splits--; } }
VideoFile LoadVideoFile(string path) { try { VideoHead vh = new VideoHead(path); if (!vh.IsBad) { VideoFile vf = new VideoFile(); vf.fileName = path; string[] ss = path.Split(System.IO.Path.DirectorySeparatorChar); vf.uid = ss[ss.Length - 2]; //предпоследняя строка UID бота (папка) vf.head = vh; return(vf); } } catch (Exception e) { } return(null); }
private void _beginConversion(VideoFile originalFile, string extension) { var originalPath = Path.Combine(_baseFolder, originalFile.Folder, $"{originalFile.FileName}.{originalFile.FileExtension}"); var newPath = FileMetadata.VerifyFileUniqueness(Path.Combine(_baseFolder, originalFile.Folder, $"{originalFile.FileName}.{extension}")); try { _mediaManager.VideoConversion(originalPath, newPath); var metadata = new FileMetadata(newPath); metadata.GetDuration(_mediaManager); var newVideoFile = metadata.MapToExistingVideoFileEntity(originalFile); _videoFileReposotroy.Update(newVideoFile); } catch { Console.Write("There Was An Error"); } }
public VideoFile Convert(string fileName, string format) { var videoFile = new VideoFile(fileName); var sourceCodec = CodecFactory.Extract(videoFile); CompressionCodec destinationCodec; if (format == "mp4") { destinationCodec = new MPEGCompressionCodec(); } else { destinationCodec = new OggCompressionCodec(); } var buffer = BitrateReader.Read(fileName, sourceCodec); var result = BitrateReader.Convert(buffer, destinationCodec); result = (new AudioMixer()).Fix(result); return(new VideoFile(result)); }
private void lvFiles_DrawItem(object sender, DrawListViewItemEventArgs e) { if (cbCaptions.SelectedIndex >= 0) { VideoFile vf = (VideoFile)e.Item.Tag; if (vf.head.Captions.Contains((string)cbCaptions.Items[cbCaptions.SelectedIndex])) { e.Graphics.FillRectangle(Brushes.LightBlue, e.Bounds); } else { e.DrawBackground(); } } else { e.DrawBackground(); } e.DrawFocusRectangle(); }
async static Task DownloadFileAsync(VideoFile videoFile, Action <int, DownloadData> updateDownload, Action <VideoFile> done) { for (var pass = 0; pass < 2; ++pass) { var found = Directory.EnumerateFiles(Settings.VideosPath).Where(path => Path.GetFileNameWithoutExtension(path).EndsWith($"{videoFile.Identifier}")).FirstOrDefault(); if (found != null) { videoFile.FileName = Path.GetFileName(found); done(videoFile); return; } if (pass != 0) { return; } await RunYouTubeDL(videoFile, updateDownload, done); } }
internal void CreateVideoIcon(VideoFile f) { string[] paths = f.Path.Split(Convert.ToChar("\\")); string name = paths[paths.Length - 1]; var item = new ListViewItem { Name = name, Text = name, Tag = f,//f.Path, BackColor = Color.Azure, SubItems = { //TODO: get time working, it doesn't want to parse f.Tags.Find(t => (Tags.GetTagType(t.TypeId).Name == "file_type")).Data, f.Tags.Find(t => (Tags.GetTagType(t.TypeId).Name == "framerate")).Data } }; fullList.Add(item); gridView.Items.Add(item); }
private void LoadVideo() { VideoFile vFile = CurrentVideo; if (vFile != null) { divVideoNotFound.Visible = false; divVideoContent.Visible = true; vPlay = ResolveUrl(vFile.VideoPath); vPlayId = vFile.Id; LoadTopVideos(); } else { divVideoNotFound.Visible = true; divVideoContent.Visible = false; } }
//Getting the Details(Video) public VideoFile GetVideoInfo(MemoryStream inputFile, string Filename) { //Create a temporary file for our use in ffMpeg string tempfile = Path.Combine(this.WorkingPath, System.Guid.NewGuid().ToString() + Path.GetExtension(Filename)); FileStream fs = File.Create(tempfile); //write the memory stream to a file and close our the stream so it can be used again. inputFile.WriteTo(fs); fs.Flush(); fs.Close(); GC.Collect(); //Video File is a class you will see further down this post. It has some basic information about the video VideoFile vf = new VideoFile(tempfile); //And, without adieu, a call to our main method for this functionality. GetVideoInfo(vf); File.Delete(tempfile); return(vf); }
public void CreateVideoThumbnails(MemoryStream inputFile, string Filename) { string tempfile = Path.Combine(this.WorkingPath, System.Guid.NewGuid().ToString() + Path.GetExtension(Filename)); FileStream fs = File.Create(tempfile); inputFile.WriteTo(fs); fs.Flush(); fs.Close(); GC.Collect(); VideoFile vf = null; try { vf = new VideoFile(tempfile); } catch(Exception ex) { throw ex; } this.CreateVideoThumbnails(vf); }
public formFramesImport(VideoFile _videoFile, long _iSelStart, long _iSelEnd, bool _bForceReload) { InitializeComponent(); m_VideoFile = _videoFile; m_iSelStart = _iSelStart; m_iSelEnd = _iSelEnd; m_bForceReload = _bForceReload; this.Text = " " + ScreenManagerLang.FormFramesImport_Title; labelInfos.Text = ScreenManagerLang.FormFramesImport_Infos + " 0 / ~?"; buttonCancel.Text = ScreenManagerLang.Generic_Cancel; progressBar.Minimum = 0; progressBar.Maximum = 100; progressBar.Step = 1; progressBar.Style = ProgressBarStyle.Blocks; progressBar.Value = 0; Application.Idle += new EventHandler(this.IdleDetector); }
public static bool ExtractAudioSegment(TASK Task) { try { Task.STATUS = (int)EnumManager.PARAM_TASK_STATUS.EN_COURS; Task.DATE_BEGIN_CONVERSION = DateTime.Now; string fileName = GetFileName(Task); CopyFileInTempFolder(fileName, Task); new TASK_Service().UpdateTask(Task); VideoFile VideoFile = new VideoFile(Task.FILE_URL_TEMP); VideoFile.GetVideoInfo(); // On set le debut du premier split TimeSpan begin = new TimeSpan(0); // on récupère la durée totale de la video long durationTotal = VideoFile.Duration.Ticks; int count = (fileName.LastIndexOf('.') + 1); fileName = fileName.Substring(0, count); Task.FILE_URL_DESTINATION = destinationFolder + @"\" + fileName + Task.FORMAT.FORMAT_NAME; // A voir pour l'extraction d'un morceau de son particulier VideoFile.ExtractAudioSegment(begin.Ticks, durationTotal, Task.FORMAT.FORMAT_NAME, Task.FILE_URL_DESTINATION); Task.STATUS = (int)EnumManager.PARAM_TASK_STATUS.EFFECTUE; Task.DATE_END_CONVERSION = DateTime.Now; new TASK_Service().UpdateTask(Task); return(true); } catch (Exception e) { Task.STATUS = (int)EnumManager.PARAM_TASK_STATUS.ERREUR; Task.DATE_END_CONVERSION = DateTime.Now; new TASK_Service().UpdateTask(Task); var trace = new TRACE() { FK_ID_TASK = Task.PK_ID_TASK, DATE_TRACE = DateTime.Now, NOM_SERVER = System.Environment.MachineName, DESCRIPTION = e.Message + " " + e.InnerException, METHOD = "Erreur lors de l'extraction audio", TYPE = "ERROR" }; new TRACE_Service().AddTrace(trace); return(false); } }
private void Window_Loaded(object sender, RoutedEventArgs e) { this.Left = Settings.Default.InitialLocation.X; this.Top = Settings.Default.InitialLocation.Y; this.WindowState = WindowState.Maximized; if (File.Exists(Settings.Default.LastFileName)) { DashCamFileTree groups = new DashCamFileTree(Settings.Default.LastFileName); VideoFile v = treeGroups.LoadTree(groups, Settings.Default.LastFileName); if (v != null && v._dashCamFileInfo.HasGpsInfo) //initial location { MainMap.Position = v._dashCamFileInfo.Position(0); MainMap.Zoom = 16; } } //FIRST time ONLY - fit width after file opened //I need <reset> to remove this action after both controls adjusted VideoStartedPostAction = (player, reset) => { player.FitWidth(false); if (_dashCamFileInfo.HasGpsInfo) { MainMap.Position = _dashCamFileInfo.Position(0); MainMap.Zoom = 16; } //reset this action until next time if (reset) { VideoStartedPostAction = (p, r) => { } } ; }; waitScreen.Hide(); }
// This adds all video files in a directory to the database and returns them in a list private List <VideoFile> MapContainedVideoFiles(DirectoryInfo dir, int parentId) { // Get the list to store successful additions List <VideoFile> files = new List <VideoFile>(); // Get all supported file extensions string[] extensions = GetSupportedFileExtensions(); // For each supported extension: for (int i = 0; i < extensions.Length; i++) { // Get all contained video files of the same type FileInfo[] videoFiles = dir.GetFiles("*." + extensions[i]); // For each video file with the current extension: for (int j = 0; j < videoFiles.Length; j++) { // Create a database VideoFile object for the file VideoFile file = new VideoFile(videoFiles[j].FullName, GetDefaultTags(videoFiles[j])); // Try to add the file to the database Response response = Files.AddFile(file, parentId, true); // Report if file addition was unsuccessful if (response == Response.Success) { file = GetAddedVideoFile(file.Path); Files.AssociateFileLocation(file, parentId); files.Add(file); } else { Console.WriteLine("Files table addition failed:\n " + videoFiles[j].FullName); } } } Console.WriteLine(files.Count + " video files found"); return(files); }
internal Result <ICameraFile> Create( CameraFilePath filePath, IEnumerable <ITag> metadata) { switch (filePath.GetExtension().ToLowerInvariant()) { case ".jpg": case ".jpeg": case ".cr2": return(ImageFile.Create(filePath, metadata)); case ".dng": return(DngImageFile.Create(filePath, metadata)); case ".mp4": case ".mov": return(VideoFile.Create(filePath, metadata)); default: throw new InvalidPathException($"Unknown file type {filePath}"); } }
public ActionResult AddLession(Lession model, HttpPostedFileBase file) { var temp = db.Lessions.Where(l => l.CourseID == model.CourseID && l.Title == model.Title).FirstOrDefault(); if (temp != null) { return Redirect("/Admin/AdminMessage?msg=该课时已经存在!"); } var radom = DateHelper.GetTimeStamp(); var course = db.Courses.Find(model.CourseID); string root = "~/Lessions/" + course.Title + "/"; var phicyPath = HostingEnvironment.MapPath(root); file.SaveAs(phicyPath + file.FileName); var exten = Path.GetExtension(file.FileName); if (!exten.Equals(".flv")) { var video = new VideoFile(phicyPath + file.FileName); video.Convert(".flv", Quality.Medium).MoveTo(phicyPath + radom + ".flv"); model.Path = fileServer + "Lessions/" + course.Title + "/" + radom + ".flv"; if (System.IO.File.Exists(phicyPath + file.FileName)) { //如果存在则删除 System.IO.File.Delete(phicyPath + file.FileName); } } else { model.Path = fileServer + "Lessions/" + course.Title + "/" + file.FileName; } // model.Path = fileServer + "Lessions/" + course.Title + "/" + file.FileName; model.Time = DateTime.Now; model.ContentType = file.ContentType; model.Browses = 0; model.Route = 1; db.Lessions.Add(model); db.SaveChanges(); return Redirect("/Admin/CourseShow/" + model.CourseID); }
public void CreateVideoThumbnails(VideoFile input) { if(!input.infoGathered) { GetVideoInfo(input); } OutputPackage ou = new OutputPackage(); //set up the parameters for getting a previewimage string filename; string finalpath; string Params; int secs; double[] previewPercentages = new double[] { .05, .15, .25, .35, .45, .55, .65, .75, .85, .95 }; foreach(double previewPercentage in previewPercentages) { secs = (int)Math.Round(TimeSpan.FromTicks((long)(input.Duration.Ticks * previewPercentage)).TotalSeconds, 0); filename = string.Format("{0}.jpg", secs.ToString()); finalpath = Path.Combine(this.WorkingPath, filename); Params = string.Format("-i {0} -ss {1} -vcodec mjpeg -vframes 1 -an {2} -f rawvideo", input.Path, secs, finalpath); this.RunProcess(Params); } }
public VideoFile GetVideoInfo(string inputPath) { VideoFile vf = null; try { vf = new VideoFile(inputPath); } catch(Exception ex) { throw ex; } GetVideoInfo(vf); return vf; }
protected void Page_Load(object sender, EventArgs e) { LabelMain.Text = GetContent("Body"); LabelRightSideBarArea.Text = "<span class=\"subtitle\">By Month</span><br />"; TagList pageTagList = null; List<Document> SideBarList = null; List<Document> DocumentList = null; if (null == Session["EditjudekGallery"]) { DocumentList = Cache.Get("cache.judek.MultimediaFiles") as List<Document>; SideBarList = Cache.Get("cache.judek.MultimediaSideBar") as List<Document>; pageTagList = Cache.Get("cache.judek.MultimediaTagList") as TagList; } if ((null == DocumentList) || (null == SideBarList) || (null == pageTagList)) {//Means that there is no cache read everything from disk #region ReadLoop DocumentList = new List<Document>(); SideBarList = new List<Document>(); pageTagList = new TagList(); DirectoryInfo directoryInfo = new DirectoryInfo(Server.MapPath(Document.MULTIMEDIA_FOLDER)); List<FileInfo> multimediaFileList = new List<FileInfo>(); multimediaFileList.AddRange(directoryInfo.GetFiles("*.mp3")); multimediaFileList.AddRange(directoryInfo.GetFiles("*.wma")); multimediaFileList.AddRange(directoryInfo.GetFiles("*.aac")); multimediaFileList.AddRange(directoryInfo.GetFiles("*.ac3")); multimediaFileList.AddRange(directoryInfo.GetFiles("*.mp4")); multimediaFileList.AddRange(directoryInfo.GetFiles("*.wmv")); multimediaFileList.AddRange(directoryInfo.GetFiles("*.mpg")); Document doc; System.Collections.Hashtable ht2 = new System.Collections.Hashtable(); foreach (FileInfo file in multimediaFileList) { try { if ((file.Extension.ToLower() == ".mp4") || (file.Extension.ToLower() == ".wmv") || (file.Extension.ToLower() == ".mpg")) doc = new VideoFile(this, file.Name); else doc = new AudioFile(this, file.Name); foreach (Tag t in doc.Tags) { pageTagList.Add(t); } //doc.Link = Document.MULTIMEDIA_FOLDER + "/" + doc.Name; doc.Link = doc.Name; } catch { continue; } DocumentList.Add(doc); #region Fill RightSideBar if (null == SideBarList.Find(delegate(Document st) { return ((st.Dated.Year == doc.Dated.Year) && (st.Dated.Month == doc.Dated.Month)); })) { SideBarList.Add(doc); } #endregion } #endregion #region Sort //Sort by date - sort should always be done after all filters for performance DocumentList.Sort(delegate(Document f1, Document f2) { return DateTime.Compare(f2.Dated, f1.Dated); }); //Do the same for right side bar SideBarList.Sort(delegate(Document f1, Document f2) { return DateTime.Compare(f2.Dated, f1.Dated); }); //And left pageTagList.Sort(delegate(ListedTag t1, ListedTag t2) { return t1.Name.CompareTo(t2.Name); }); #endregion #region Insert Cache //Fill the cache with newly read info. Cache.Insert("cache.judek.MultimediaFiles", DocumentList); Cache.Insert("cache.judek.MultimediaSideBar", SideBarList); Cache.Insert("cache.judek.MultimediaTagList", pageTagList); #endregion } #region Filter try { //Try and do all filters here at once for performance if (Request.QueryString["perma"] != null) { string permaFilter = Request.QueryString["perma"]; DocumentList = DocumentList.FindAll(delegate(Document d) { return ((d.Name.ToLower() == permaFilter.ToLower())); }); } else if (Request.QueryString["MonthFilter"] != null) { string MonthFilter = Request.QueryString["MonthFilter"]; if (MonthFilter.Length == 6) { int nYearFilter = Int32.Parse(MonthFilter.Substring(0, 4)); int nMonthFilter = Int32.Parse(MonthFilter.Substring(4, 2)); DocumentList = DocumentList.FindAll(delegate(Document d) { return ((d.Dated.Month == nMonthFilter) && (d.Dated.Year == nYearFilter)); }); } } else if (Request.QueryString["Tags"] != null) { string sTag = Request.QueryString["Tags"]; DocumentList = DocumentList.FindAll(delegate(Document d) { return d.Tags.HasTag(sTag); }); } else ;//no filter } catch { } #endregion #region Body Write Loop //Show just 25 entries maximum for (int i = 0; ((i < 25) && (i < DocumentList.Count)); i++) { MultimediaFile d = DocumentList[i] as MultimediaFile; if (null == d) continue; LabelMultiMediaFiles.Text += "<br><span class=\"subtitle\" >"; string slink; if (d.MultimediaType == MultimediaType.audio) { slink = "<br><a href=Play.aspx?FL=" + Document.MULTIMEDIA_FOLDER + "&F=" + d.Link + "&T=" + d.MultimediaType + "&W=380&H=50" + "&plugins=spectrumvisualizer-1" + " onclick=\"window.open(this.href,'newWindow','width=400,height=400', 'modal');return false\">"; } else if (d.MultimediaType == MultimediaType.video) slink = "<br><a href=Play.aspx?FL=" + Document.MULTIMEDIA_FOLDER + "&F=" + d.Link + "&T=" + d.MultimediaType + "&W=640&H=388" + " onclick=\"window.open(this.href,'newWindow','width=652,height=700', 'modal');return false\">"; else slink = ""; slink += d.Title + "</a></span>"; LabelMultiMediaFiles.Text += slink; LabelMultiMediaFiles.Text += " <br /><span class=\"footer\" >[" + d.Dated.ToLongDateString() + "] <a href=\"Multimedia.aspx?perma=" + d.Name + "\">PermaLink</a></span>"; if (d.Attachments.Count > 0) LabelMultiMediaFiles.Text += "<br /><span class=\"footer\" >Attachements:</span>"; foreach (Attachement att in d.Attachments) { LabelMultiMediaFiles.Text += " <span class=\"footer\" >(<a href=GetFile.aspx?SF=" + Document.ATTACHMENT_FOLDER + "/" + att.AttachmentInfo.Name + "&TF=" + att.Title + ">" + att.Title + "</a>)</span>"; } LabelMultiMediaFiles.Text += "<br />" + d.HTMLDescription + ""; } #endregion #region SideBar Write Loop foreach (Document SideBarDoc in SideBarList) { string sYearMonth = SideBarDoc.Dated.ToString("yyyy") + SideBarDoc.Dated.ToString("MM"); LabelRightSideBarArea.Text += string.Format("<a href=\"{2}\">{0}-{1}</a><br />", SideBarDoc.Dated.ToString("MMMM"), SideBarDoc.Dated.ToString("yyyy"), "Multimedia.aspx?MonthFilter=" + sYearMonth); } #endregion //LabelTagCloud.Text = "Categories <i>(Click any link below)</i><br />"; foreach (Tag tag in pageTagList) { LabelTagCloud.Text += string.Format(" | <a href=\"Multimedia.aspx?Tags={0}\">{1}</a> ", tag.Signature, tag.Name); } }
public void GetVideoInfo(VideoFile input) { //set up the parameters for video info string Params = string.Format("-i {0}", input.Path); string output = RunProcess(Params); input.RawInfo = output; //get duration Regex re = new Regex("[D|d]uration:.((\\d|:|\\.)*)"); Match m = re.Match(input.RawInfo); if(m.Success) { string duration = m.Groups[1].Value; string[] timepieces = duration.Split(new char[] { ':', '.' }); if(timepieces.Length == 4) { input.Duration = new TimeSpan(0, Convert.ToInt16(timepieces[0]), Convert.ToInt16(timepieces[1]), Convert.ToInt16(timepieces[2]), Convert.ToInt16(timepieces[3])); } } //get audio bit rate re = new Regex("[B|b]itrate:.((\\d|:)*)"); m = re.Match(input.RawInfo); double kb = 0.0; if(m.Success) { Double.TryParse(m.Groups[1].Value, out kb); } input.BitRate = kb; //get the audio format re = new Regex("[A|a]udio:.*"); m = re.Match(input.RawInfo); if(m.Success) { input.AudioFormat = m.Value; } //get the video format re = new Regex("[V|v]ideo:.*"); m = re.Match(input.RawInfo); if(m.Success) { input.VideoFormat = m.Value; } //get the video format re = new Regex("(\\d{2,3})x(\\d{2,3})"); m = re.Match(input.RawInfo); if(m.Success) { int width = 0; int height = 0; int.TryParse(m.Groups[1].Value, out width); int.TryParse(m.Groups[2].Value, out height); input.Width = width; input.Height = height; } input.infoGathered = true; }
protected void LoadVideoFile(IWin32Window owner) { Console.WriteLine("Please enter the filename of the video file you want to load:\r\n (this can be any video type your system supports, for instance AVI, MPEG, DivX, ...)"); string file = Console.ReadLine(); if (file != null && file != "") { mediaFile = new VideoFile(file, owner); } }
/// <summary> /// 上传视频 /// </summary> /// <param name="ProductID"></param> /// <returns></returns> public ActionResult VideoUpload(int ProductID, int? InfoID) { HttpPostedFileBase file = Request.Files[0]; if (file != null) { if (InfoID == null) { ProductUserInfo info = new ProductUserInfo(); info.Time = DateTime.Now; info.ProductID = ProductID; info.Status = ProductUserInfoStatusEnum.审核中; info.AuthorID = CurrentUser.ID; db.ProductUserInfos.Add(info); db.SaveChanges(); InfoID = info.ID; } string random = Helpers.DateHelper.GetTimeStamp(); Product product = db.Products.Find(ProductID); ProductFile productFile = new ProductFile(); productFile.ProductID = ProductID; productFile.FileTypeAsInt = 1; string root = "~/ProductFile/" + product.ID + "/"; var phicyPath = HostingEnvironment.MapPath(root); file.SaveAs(phicyPath + random + file.FileName); var exten = Path.GetExtension(file.FileName); if (!exten.Equals(".flv")) { var video = new VideoFile(phicyPath + random + file.FileName); video.Convert(".flv", Quality.Medium).MoveTo(phicyPath + random + ".flv"); productFile.Path = "/ProductFile/" + product.ID + "/" + random + ".flv"; if (System.IO.File.Exists(phicyPath + random + file.FileName)) { //如果存在则删除 System.IO.File.Delete(phicyPath + random + file.FileName); } } else { productFile.Path = "/ProductFile/" + product.ID + "/" + random + file.FileName; } productFile.PUId = InfoID; db.ProductFiles.Add(productFile); db.SaveChanges(); return Json(new { filePath = productFile.Path, PUId = InfoID }); } else { return Json(new { filePath = "" }); } }
/// <summary> /// Adds an <see cref="IVideoFile"/> to the database. /// </summary> /// <param name="fileName">File name to add.</param> /// <param name="pathId">Path ID for where the file is located.</param> /// <returns> /// Whether or not the file was added to the database. Returns <c>false</c> if the file existed already. /// </returns> private async Task<bool> AddFileAsync(string fileName, int pathId) { var videoFile = new VideoFile { FileName = fileName, PathId = pathId, PlayCount = 0 }; return await AddFileAsync(videoFile); }
protected void Page_Load(object sender, EventArgs e) { //LabelMain.Text = GetContent("Body"); LiteralPageTitle.Text = FormatPageTitle("Sermon Archive"); LabelRightSideBarArea.Text = "<span class=\"title\">Archives</span><br />"; TagList pageTagList = null; List<Document> SideBarList = null; List<Document> DocumentList = null; if (null == Session["EditRiverValleyMedia"]) { DocumentList = Cache.Get("cache.RiverValley.MultimediaFiles") as List<Document>; SideBarList = Cache.Get("cache.RiverValley.MultimediaSideBar") as List<Document>; pageTagList = Cache.Get("cache.RiverValley.MultimediaTagList") as TagList; } if ((null == DocumentList) || (null == SideBarList) || (null == pageTagList)) {//Means that there is no cache read everything from disk #region ReadLoop DocumentList = new List<Document>(); SideBarList = new List<Document>(); pageTagList = new TagList(); DirectoryInfo directoryInfo = new DirectoryInfo(Server.MapPath(Document.MULTIMEDIA_FOLDER)); List<FileInfo> multimediaFileList = new List<FileInfo>(); multimediaFileList.AddRange(directoryInfo.GetFiles("*.mp3")); multimediaFileList.AddRange(directoryInfo.GetFiles("*.wma")); multimediaFileList.AddRange(directoryInfo.GetFiles("*.aac")); multimediaFileList.AddRange(directoryInfo.GetFiles("*.ac3")); multimediaFileList.AddRange(directoryInfo.GetFiles("*.mp4")); multimediaFileList.AddRange(directoryInfo.GetFiles("*.wmv")); multimediaFileList.AddRange(directoryInfo.GetFiles("*.mpg")); Document doc; System.Collections.Hashtable ht2 = new System.Collections.Hashtable(); foreach (FileInfo file in multimediaFileList) { try { if ((file.Extension.ToLower() == ".mp4") || (file.Extension.ToLower() == ".wmv") || (file.Extension.ToLower() == ".mpg")) doc = new VideoFile(this, file.Name); else doc = new AudioFile(this, file.Name); foreach (Tag t in doc.Tags) { pageTagList.Add(t); } //doc.Link = Document.MULTIMEDIA_FOLDER + "/" + doc.Name; doc.Link = doc.Name; } catch { continue; } DocumentList.Add(doc); #region Fill RightSideBar if (null == SideBarList.Find(delegate(Document st) { return ((st.Dated.Year == doc.Dated.Year) && (st.Dated.Month == doc.Dated.Month)); })) { SideBarList.Add(doc); } #endregion } #endregion #region Sort //Sort by date - sort should always be done after all filters for performance DocumentList.Sort(delegate(Document f1, Document f2) { return DateTime.Compare(f2.Dated, f1.Dated); }); //Do the same for right side bar SideBarList.Sort(delegate(Document f1, Document f2) { return DateTime.Compare(f2.Dated, f1.Dated); }); //And left pageTagList.Sort(delegate(ListedTag t1, ListedTag t2) { return t1.Name.CompareTo(t2.Name); }); #endregion #region Insert Cache //Fill the cache with newly read info. Cache.Insert("cache.RiverValley.MultimediaFiles", DocumentList); Cache.Insert("cache.RiverValley.MultimediaSideBar", SideBarList); Cache.Insert("cache.RiverValley.MultimediaTagList", pageTagList); #endregion } #region Filter try { //Try and do all filters here at once for performance if (Request.QueryString["perma"] != null) { string permaFilter = Request.QueryString["perma"]; DocumentList = DocumentList.FindAll(delegate(Document d) { return ((d.Name.ToLower() == permaFilter.ToLower())); }); } else if (Request.QueryString["MonthFilter"] != null) { string MonthFilter = Request.QueryString["MonthFilter"]; if (MonthFilter.Length == 6) { int nYearFilter = Int32.Parse(MonthFilter.Substring(0, 4)); int nMonthFilter = Int32.Parse(MonthFilter.Substring(4, 2)); DocumentList = DocumentList.FindAll(delegate(Document d) { return ((d.Dated.Month == nMonthFilter) && (d.Dated.Year == nYearFilter)); }); } } else if (Request.QueryString["Tags"] != null) { string sTag = Request.QueryString["Tags"]; DocumentList = DocumentList.FindAll(delegate(Document d) { return d.Tags.HasTag(sTag); }); } else if (Request.QueryString["YearFilter"] != null) { int YearView; if (true == Int32.TryParse(Request.QueryString["YearFilter"], out YearView)) { DocumentList = DocumentList.FindAll(delegate(Document d) { return d.Dated.Year == YearView; }); } } else { }//no filter } catch { } #endregion #region Body Write Loop //Show just 25 entries maximum for (int i = 0; ((i < 25) && (i < DocumentList.Count)); i++) { MultimediaFile d = DocumentList[i] as MultimediaFile; if (null == d) continue; LabelMultiMediaFiles.Text += "<br><span class=\"subtitle\" >"; string slink; if (d.MultimediaType == MultimediaType.audio) { //slink = "<br /><a href=MultimediaPlay.aspx?FL=" + Document.MULTIMEDIA_FOLDER + "&F=" + d.Link + "&T=" + d.MultimediaType + "&W=380&H=50" + "&plugins=spectrumvisualizer-1" + " onclick=\"window.open(this.href,'newWindow','width=400,height=400', 'modal');return false\">"; slink = "<br /><a href=MultimediaPlay.aspx?FL=" + Document.MULTIMEDIA_FOLDER + "&F=" + d.Link + "&T=" + d.MultimediaType + "&W=380&H=50" + "&plugins=spectrumvisualizer-1" + ">"; } else if (d.MultimediaType == MultimediaType.video) { slink = "<br /><a href=MultimediaPlay.aspx?FL=" + Document.MULTIMEDIA_FOLDER + "&F=" + d.Link + "&T=" + d.MultimediaType + "&W=640&H=388" + ">"; } else { slink = ""; } slink += d.Title + "</a></span>"; LabelMultiMediaFiles.Text += slink; LabelMultiMediaFiles.Text += " <br /><br /><span class=\"footer\" >[" + d.Dated.ToLongDateString() + "] <a href=\"Multimedia.aspx?perma=" + d.Name + "\">PermaLink</a></span>"; if (d.Attachments.Count > 0) LabelMultiMediaFiles.Text += "<br /><span class=\"footer\" >Attachements:</span>"; foreach (Attachement att in d.Attachments) { LabelMultiMediaFiles.Text += " <span class=\"footer\" >(<a href=GetFile.aspx?SF=" + Document.ATTACHMENT_FOLDER + "/" + att.AttachmentInfo.Name + "&TF=" + att.Title + ">" + att.Title + "</a>)</span>"; } //LabelMultiMediaFiles.Text += "<br />" + d.HTMLDescription + ""; string sDescription = ContentReader.FormatTextBlock(d.Description); if (sDescription.Length > 500) sDescription = sDescription.Substring(0, 500) + "..."; LabelMultiMediaFiles.Text += "<br />" + sDescription; } #endregion #region SideBar Write Loop int yearView = DateTime.Now.Year; if (Request.QueryString["YearFilter"] != null) { if (false == Int32.TryParse(Request.QueryString["YearFilter"], out yearView)) { yearView = DateTime.Now.Year; } } List<int> yearsPrinted = new List<int>(); foreach (Document SideBarDoc in SideBarList) { if (SideBarDoc.Dated.Year == yearView) { string sYearMonth = SideBarDoc.Dated.ToString("yyyy") + SideBarDoc.Dated.ToString("MM"); LabelRightSideBarArea.Text += string.Format("<span class=\"subtitle\"><a href=\"{2}\">{0}-{1}</a></span><br />", SideBarDoc.Dated.ToString("MMMM"), SideBarDoc.Dated.ToString("yyyy"), "Multimedia.aspx?MonthFilter=" + sYearMonth); } else { int j = yearsPrinted.Find(delegate(int i) { return i == SideBarDoc.Dated.Year; }); if (j != SideBarDoc.Dated.Year) { yearsPrinted.Add(SideBarDoc.Dated.Year); LabelRightSideBarArea.Text += string.Format("<span class=\"title\"><a href=\"Multimedia.aspx?YearFilter={0}\">{0}</a></span><br />", SideBarDoc.Dated.Year); } } } #endregion string sThisFileName = System.IO.Path.GetFileName(Request.Url.AbsolutePath); string PodcastPageURL = (Request.Url.AbsoluteUri).Replace(sThisFileName, "Podcast.aspx"); //Remove any query strings int nQueryBegin = PodcastPageURL.IndexOf('?'); if (nQueryBegin > 0) PodcastPageURL = PodcastPageURL.Substring(0, nQueryBegin); //LabelTagCloud.Text = "Categories <i>(Click any link below)</i><br />"; //LabelTagCloud.Text += "<br /><a href=\"" + PodcastPageURL + "\" target=_blank><img border=0 src=picts/feed-icon-14x14.png alt=\"Sermon rss feed\" /> Podcast</a><br />"; LabelTagCloud.Text += "<br /><a href=\"" + "Podcast.aspx" + "\" target=_blank><img border=0 src=picts/feed-icon-14x14.png alt=\"Sermon rss feed\" /> Podcast</a><br />"; foreach (Tag tag in pageTagList) { LabelTagCloud.Text += string.Format(" | <a href=\"Multimedia.aspx?Tags={0}\">{1}</a> ", tag.Signature, tag.Name); } }
public void CreateVideoThumbnails(string inputPath) { VideoFile vf = null; try { vf = new VideoFile(inputPath); } catch(Exception ex) { throw ex; } this.CreateVideoThumbnails(vf); }
public ActionResult AddProductVideo(int ProductID, HttpPostedFileBase file) { if (CurrentUser.Role == Role.Admin) { if (file != null) { string random = Helpers.DateHelper.GetTimeStamp(); Product product = db.Products.Find(ProductID); ProductFile productFile = new ProductFile(); productFile.ProductID = ProductID; productFile.FileTypeAsInt = 1; productFile.Source = SourceEnum.管理员; productFile.IsUse = true; string root = "~/ProductFile/AdminFiles/" + product.ID + "/"; var phicyPath = HostingEnvironment.MapPath(root); file.SaveAs(phicyPath + random + file.FileName); var exten = Path.GetExtension(file.FileName); if (!exten.Equals(".flv")) { var video = new VideoFile(phicyPath + random + file.FileName); video.Convert(".flv", Quality.Medium).MoveTo(phicyPath + random + ".flv"); productFile.Path = "/ProductFile/AdminFiles/" + product.ID + "/" + random + ".flv"; if (System.IO.File.Exists(phicyPath + random + file.FileName)) { //如果存在则删除 System.IO.File.Delete(phicyPath + random + file.FileName); } } else { productFile.Path = "/ProductFile/AdminFiles/" + product.ID + "/" + random + file.FileName; } db.ProductFiles.Add(productFile); db.SaveChanges(); return Redirect("/Admin/ProductShow/" + ProductID); } else { return Redirect("/Admin/AdminMessage?msg=你没有选择视频文件"); } } else { if (file != null) { string random = Helpers.DateHelper.GetTimeStamp(); //Product product = db.Products.Find(ProductID); ProductFile productFile = new ProductFile(); productFile.FileTypeAsInt = 1; productFile.Source = SourceEnum.用户; productFile.IsUse = false; productFile.PUId = ProductID; string root = "~/ProductFile/UserFiles/" + ProductID + "/"; var phicyPath = HostingEnvironment.MapPath(root); file.SaveAs(phicyPath + random + file.FileName); var exten = Path.GetExtension(file.FileName); if (!exten.Equals(".flv")) { var video = new VideoFile(phicyPath + random + file.FileName); video.Convert(".flv", Quality.Medium).MoveTo(phicyPath + random + ".flv"); productFile.Path = "/ProductFile/UserFiles/" + ProductID + "/" + random + ".flv"; if (System.IO.File.Exists(phicyPath + random + file.FileName)) { //如果存在则删除 System.IO.File.Delete(phicyPath + random + file.FileName); } } else { productFile.Path = "/ProductFile/UserFiles/" + ProductID + "/" + random + file.FileName; } db.ProductFiles.Add(productFile); db.SaveChanges(); return Redirect("/Admin/UseProductShow/" + ProductID); } else { return Redirect("/Admin/AdminMessage?msg=你没有选择视频文件"); } } }