問題描述
我允許用戶上傳視頻,然后使用 ffmpeg 進行轉換.視頻轉換需要很長時間,這通常會導致錯誤.我已經完成了我的研究,但不知道應該從哪里開始.
I allow users to upload videos and then they get converted using ffmpeg. The video takes a really long time to convert which usually results in an error. I have done my research with no luck as to where I should get started.
基本上我想要做的是允許用戶上傳視頻,然后顯示一條消息,表示正在處理視頻,您將在可用時收到通知.同時,我希望視頻在幕后進行轉換,并允許用戶離開頁面甚至關閉瀏覽器.我使用的是 Windows 服務器.
Basically what I want to do is allow the user to upload the video and then display a message that says video is being processed and you will be notified when available. In the meantime I want the video to be converted behind the scenes and allow the user to leave the page or even close the browser. I am using a Windows server.
我怎樣才能做到這一點?
How can I accomplish this?
推薦答案
以下是如何使用 Cron 等調度系統創建自己的隊列的基本概要:
Here is a basic run-down of how to make your own queue using a scheduling system such as Cron:
- 創建一個包含
(id, created_at, file_path, id_user, result, error)
的數據庫表queue
.file_path
包含要處理的上傳視頻的位置,處理前結果為null
,然后根據成功情況為true/false
,以及如果失敗error
包含任何消息.如果合適,用戶表的主鍵也可以保存在這里. - 每分鐘運行一個 Cron 程序來檢查隊列中是否有任何未處理的項目.
- 如果有項目在等待,請遍歷其中的一些項目并運行您的視頻轉換代碼.您可能希望將其限制為一次處理不超過五個項目,并且任何更多排隊的項目都必須等待新的 cron 運行.
- 在您的 cron 腳本開始時,如果舊副本已經在運行,您需要提前退出.您可以使用
ps aux | 的輸出.如果您在類似 *nix 的操作系統中運行,grep (scriptname)
可以提供幫助.
- Create a database table
queue
containing(id, created_at, file_path, id_user, result, error)
. Thefile_path
contains the location of the uploaded video to process, the result isnull
before processing and thentrue/false
afterwards depending on success, and if it failederror
contains any messages. The primary key of the user table can be saved here too, if appropriate. - Every minute, run a Cron program to check the queue for any unprocessed items.
- If there are items waiting, loop through a few of them and run your video conversion code. You may wish to limit this so that no more than, say, five items are processed in one go, and any more queued items have to wait for a new cron run.
- At the start of your cron script you need to exit early if an old copy is already running. You can use the output of
ps aux | grep (scriptname)
to help here, if you are running in a *nix-like operating system.
在您的 Web 應用程序中,您需要稍微修改工作流程 - 而不是期望立即處理視頻,您需要:
Inside your web application, you need to somewhat modify the workflow - rather than expecting a video to be processed immediately, you need to:
- 通過創建新的數據庫行請求視頻轉換
- 重定向到說明正在創建視頻的頁面
- 使用網絡重定向、AJAX 或網絡套接字定期重新檢查轉換狀態.
這種方法對于無法安裝自己的隊列處理器的共享主機非常有用.但是,如果您使用的是 VPS 或云系統,您可能希望查看 Gearman 或許多其他排隊系統之一.它們比上面的要復雜一些,但具有更多用于管理工作隊列的功能.
This approach is very useful for shared hosting where you cannot install your own queue processors. However, if you are on a VPS or cloud system, you may wish to look into Gearman or one of many other queueing systems. They are a bit more complex than the above, but have more features for managing queues of work.
這篇關于如何使用 PHP 和 ffmpeg 在后臺轉換視頻的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!