本文将告訴你如何建立網站的php部分以及如何使用flex架構建立一個視訊播放器。要建立一個youtube的簡單版本(我們可以稱它為mytube),你需要有一些适當的工具。
在伺服器端,你需要php 和mysql。mysql是用來存儲有關視訊的資料的(比如視訊的檔案名,縮略圖,縮略圖的高度和寬度,标題和描述)。php将完成格式化頁面的工作,包括html和xml頁面,這取決于你想要怎麼做。
你還需要一個開源的軟體:ffmpeg,它可以将使用者上傳的任何格式的視訊檔案轉換成flashvideo檔案(flv)。當你向使用者展示一個可用的視訊清單時,這個 ffmpeg軟體還可以生成視訊中某一幀的縮略圖。毫無疑問,在視訊分享的世界中ffmpeg會是你最好的助手。它是一個功能強大、易于使用而且文檔齊全的極為優秀的軟體。
在用戶端,有幾種不同的使用者界面可供選擇。第一種就是類似于youtube的html/flash混合式的使用者界面,另外一種就是完全基于flash的使用者界面。這裡我選擇了flex架構來建立一個flash程式,這個程式首先播放視訊,然後會列出一個可用視訊的清單并提供導航。
建立php背景
建立背景的程式之前,你必須先在mysql建立一些資料庫模式(schema)。首先,建立一個資料庫,你可以使用mysqladmin指令行:
複制内容到剪貼闆
<code>mysqladmin create movies</code>
完成之後,将模式加載到資料庫,模式檔案内容如下:
movies.sql複制内容到剪貼闆
<code>drop table if exists movies; create table movies ( movieid integer not null auto_increment, title varchar( 255 ), source varchar( 255 ), thumb varchar( 255 ), width integer, height integer, primary key( movieid ) );</code>
要向資料庫中添加資料,你需要開發一個html上傳頁面,它可以上傳視訊,将視訊轉換成flashvideo,獲得一個縮略圖并将這些資訊添加到資料庫中。
建立上傳頁面
事實上,建立一個上傳視訊的html頁很簡單,如下:
addmovie.html複制内容到剪貼闆
<code><html> <body> <form enctype="multipart/form-data" method="post"action="upload.php"> <input type="hidden" name="max_file_size"value="300000" /> <table> <tr><td>title</td><td><inputtype="text"name="title"></td></tr> <tr><td>movie</td><td><inputtype="file"name="movie"></td></tr> </table> <input type="submit" value="upload"/> </form> </body> </html></code>
這個頁面的表單送出到 upload.php 頁,upload.php會處理視訊,抓取縮略圖并将資料添加到資料庫中。頁面代碼如下:
upload.php複制内容到剪貼闆
<code><html><body> <?php require "db.php"; function converttoflv( $in, $out ) { unlink( $out ); $cmd = "ffmpeg -v 0 -i $in -ar11025 $out 2>&1"; $fh = popen( $cmd, "r"); while( fgets( $fh ) ) {} pclose( $fh ); } function getthumbnail( $in, $out ) { unlink( $out ); $cmd = "ffmpeg -i $in -pix_fmtrgb24 -vframes 1 -s 300x200 $out2>&1"; $fh = popen( $cmd, "r"); while( fgets( $fh ) ) {} pclose( $fh ); } function flv_import( $upfile, $fname, $title ) { $fname = preg_replace('/\..*$/', '', basename( $fname ) ); $flvpath = "$fname.flv"; $thumbpath ="$fname.gif"; converttoflv( $upfile,"movies\\$flvpath" ); getthumbnail( $upfile,"movies\\$thumbpath" ); $dsn ='mysql://root@localhost/movies'; $db =&db::connect( $dsn ); if ( pear::iserror( $db ) ) {die($db->getmessage()); } $sth =$db->prepare( 'insert into movies values ( 0, ?, ?,?, ?, ? )' ); $db->execute($sth, array( $title, $flvpath, $thumbpath, 300, 200 ) ); } flv_import( $_files['movie']['tmp_name'], $_files['movie']['name'],$_post['title'] ); ?> file sucessfully uploaded </body></html></code>
函數flv_import()是腳本代碼的核心部分,它調用了converttoflv() 函數和getthumbnail()函數來将視訊轉換成flashvideo檔案和建立縮略圖。然後它向資料庫中添加了有關視訊的一些資料。有關flv和縮略圖的功能都使用了 ffmpeg中的指令行來處理視訊。
當我打開addmovie.html 頁面的時候,我做了一下截圖,見圖1.