The flv video website uses Flex and PHP to create its own video application.
Original article address:
Http://www.onlamp.com/pub/a/php/... h-flex-and-php.html
Author: Jack Herrington
With the popularity of broadband, the price of hard disk space continues to decrease, and Adobe®Flash®It is not surprising that Video sharing is so popular on the Internet. Websites like Google video and YouTube are the leader, and now small video sharing sites are everywhere. So how can we join the trend? How can I use PHP, Flash, and Adobe Flex? And other technologies to create your own video sharing website? It's much easier than you think.
This article will show you how to create a website's PHP section and how to use the Flex framework to create a video player. To create a simple version of YouTube (we can call it MyTube), you need some appropriate tools.
On the server side, you need PHP and MySQL. MySQL is used to store video data (such as video file names, thumbnails, height and width of thumbnails, titles, and descriptions ). PHP will complete page formatting, including HTML and XML pages, depending on what you want to do.
You also need an open-source software: ffmpeg, which can convert any Video files uploaded by users into Flash Video files (FLV ). When you display a list of available videos to users, the ffmpeg software can also generate thumbnails of a certain frame in the video. There is no doubt that ffmpeg will be your best assistant in the world of video sharing. It is a powerful, easy-to-use and well-documented software.
There are several different user interfaces available on the client. The first is a user interface similar to YouTube's HTML/Flash hybrid, and the other is a user interface completely based on Flash. Here I chose the Flex framework to create a Flash program. this program first plays the video and then lists a list of available videos and provides navigation.
Create a PHP background
Before creating a background program, you must first create some database schema in MySQL ). First, create a database. you can use the mysqladmin command line: copy the content to the clipboard code: mysqladmin create movies
After completion, load the mode to the database. the content of the mode file is as follows:
Movies. copy the content to the clipboard 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)
);
To add data to a database, you need to develop an HTML upload page, which can upload videos, convert videos to Flash videos, obtain a thumbnail, and add the information to the database.
Create Upload page
In fact, creating an HTML page for video uploading is simple, as shown below:
Addmovie.html:
The form on this page is submitted to the upload. php page. upload. php processes the video, captures the thumbnail, and adds the data to the database. The page code is as follows:
Upload. php:
Require "DB. php ";
Function converttoflv ($ in, $ out)
{
Unlink ($ out );
$ Cmd = "ffmpeg-v 0-I $ in-ar 11025 $ out 2> & 1 ";
$ Fh = popen ($ cmd, "r ");
While (fgets ($ fh )){}
Pclose ($ fh );
}
Function getthumbnail ($ in, $ out)
{
Unlink ($ out );
$ Cmd = "ffmpeg-I $ in-pix_fmt rgb24-vframes 1-s 300x200 $ out 2> & 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 = "Hangzhou 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 ());}
$ Something = $ db-> prepare ('Insert INTO movies VALUES (0 ,?, ?, ?, ?, ? )');
$ Db-> execute ($ TH, array ($ title, $ flvpath, $ thumbpath, 300,200 ));
}
Flv_import ($ _ FILES ['movie '] ['tmp _ name'], $ _ FILES ['movie'] ['name'], $ _ POST ['title']);
?>
File sucessfully uploaded
The flv_import () function is the core part of the script code. it calls the converttoflv () function and the getthumbnail () function to convert the Video into a Flash Video file and create a thumbnail. Then it adds video-related data to the database. The FLV and thumbnail functions both use the command line in ffmpeg to process videos.
When I opened the addmovie.html page, I did it. see.
. Upload Video Page Now you can click the Upload button to Upload the video to the server for processing.
The script on the upload. php page is just some basic code. To put it into use, you need to add some error verification code. The biggest problem with these scripts is the ability to process large video files. Large video files need to be converted for a long time, and users also need to wait for a long time.
To support large video files (such as videos longer than 10 seconds), we recommend that you simply copy the video to a folder, then, notify the user that the video will appear on the website later. Then you can write a script to process the video in the folder.
Here I think it is necessary to explain why the Video should be converted to Flash Video. Of course, in Flash Player, I need to use Flash Video to watch the Video. But it's not just that. if I don't want to convert it, I need to show what the player is for each video and help the user find and install the player suitable for their system. This requires a lot of work. What is the biggest advantage of converting all videos into Flash videos ?? What is the biggest advantage of Flash Player compiled using Flex ?? That is, it can run almost anywhere.
The next step is to create a simple HTML/Flash interface similar to YouTube.
Create HTML/Flash interface
In Adobe Flex Builder? 2. create a new Flex project, and then create a Flash video. The video is found and played through the specified URL. We name this Flex application file simplemovie. mxml. the code is as follows:
Simplemovie. mxml:
Source = "{Application. application. parameters. movie}"/>
This simple Flex program includes two parts: a VideoDisplay component used to Play a video and a Play button. when the video is played, you can click the button to Play it again.
The VideoDisplay component has a source attribute that contains the URL address of the Video FLV file. Here, its value is a program variable, which is in HTMLOrProvided by the FlashVars attribute of the tag.
Use Flex builderto compile simplemovie.mxmlinto the simplemovie.swf file and then move it from the bin folder to the PHP file directory. The following code creates a PHP page embedded in this video:
Copy the content of simptest. php to the clipboard code: Require "DB. php ";
$ Moviebase = 'http: // localhost: 8080/movies /';
$ Dsn = 'MySQL: // root @ localhost/movies ';
$ Db = & DB: connect ($ dsn );
If (PEAR: isError ($ db) {die ($ db-> getMessage ());}
$ Source = null;
$ MovieId = 1;
If (array_key_exists ('movi', $ _ GET ))
$ MovieId = $ _ GET ['movi'];
$ Movies = array ();
$ Res = $ db-> query ('select movieId, source, title FROM movies ');
While ($ row = $ res-> fetchrow ()){
$ Movies [] = $ row;
If ($ row [0] ==$ movieId)
$ Source = $ row [1];
}
If ($ source = null)
$ Source = $ movies [0] [1];
?>
Height = "335"
Codebase = "http://fpdownload.macromedia.com/get/flashplayer/current/
Swflash. cab ">
Width = "400" height = "335" play = "true"
Loop = "false"
Quality = "high"
FlashVars = "movie = "
Type = "application/x-shockwave-flash"
Pluginspage = "http://www.adobe.com/go/getflashplayer">
|
Foreach ($ movies as $ movie ){
?>
">
}
?>
|
In the above code, connect to the database and obtain the video list. Hosts file.
Next, createAndThe tag is embedded in simplemovie.swf. The tag also provides the correct URL of the video. Then, a list is created to list all available video frequencies. each item in the list provides the correct ID of the corresponding video and links it to this page.
Result 2 of running this page in a browser:
. Simple video player and video list When I open the page, the first video starts playing. When I select a video in the list on the right, the page will reload and play the selected video.
Is it easy? A Flex file, a PHP file, and some background database operations. wow! A video sharing website appears!
Next, we will do some work in Flex to enhance the user experience.
Flex interface, part 1
If you want Flex to play a video, you must provide the video list to the Flex program. The easiest way is to use XML. So now we want to return to the PHP section and write a page that extracts the video list from the database to the XML file. Movies. php implements this function. the code is as follows:
Movies. php: Require "DB. php ";
$ Moviebase = 'http: // localhost: 8080/movies /';
Header ('content-type: text/XML ');
$ Dsn = 'MySQL: // root @ localhost/movies ';
$ Db = & DB: connect ($ dsn );
If (PEAR: isError ($ db) {die ($ db-> getMessage ());}
?> $ Res = $ db-> query ('select title, source, thumb, width, height FROM movies ');
While ($ row = $ res-> fetchrow ()){
?>
Thumb =" "Width =" "
Height =" "/> }
?>
You can run it through the command line to view the generated XML, or open this page in the browser, and then you can see the XML displayed in a tree. see:
. XML list of videos With this XML list, we can create a Flex program extended from simplemovie. mxml. the code is as follows:
Copy the content of mytube1.mxml to the clipboard code:
Import mx. rpc. events. ResultEvent;
Import mx. controls. VideoDisplay;
Import mx. controls. List;
Import mx. rpc. http. HTTPService;
Import mx. collections. ArrayCollection;
[Bindable]
Private var movies: ArrayCollection = new ArrayCollection ();
Public function onGetMovies (event: ResultEvent): void
{
Var firstMovie: String = event. result. movies. movie [0]. source. toString ();
VideoPlayer. source = firstMovie;
Movies = event. result. movies. movie;
MovieList. selectedIndex = 0;
}
Public function onPrevious (): void
{
If (movieList. selectedIndex = 0)
MovieList. selectedIndex = movies. length-1;
Else
MovieList. selectedIndex-= 1;
VideoPlayer. source = this. movieList. selectedItem. source. toString ();
}
Public function onPlay (): void
{
VideoPlayer. source = this. movieList. selectedItem. source. toString ();
VideoPlayer. play ();
}
Public function onNext (): void
{
If (movieList. selectedIndex> = (movies. length-1 ))
MovieList. selectedIndex = 0;
Else
MovieList. selectedIndex + = 1;
VideoPlayer. source = this. movieList. selectedItem. source. toString ();
}
Public function onChange (): void
{
VideoPlayer. source = this. movieList. selectedItem. source. toString ();
}
DataProvider = "{movies }"
Change = "onChange ()"
LabelField = "title">
The obvious change is that a lot of ActionScript code is added to the upper part of the page to manage the interface. The code first reads XML from movies. php using HTTPService in onGetMovies. When the HTTPService class detects XML, it immediately returns an XML Document Object Model (DOM). then we can use this DOM to read the first video and play it. The onGetMovies () function also sets a movies variable to store the video to be displayed in the list box. Other methods in the ActionScript code process different events that may be triggered on the interface, such as clicking the video list, clicking the "previous" or "next" button.
The bottom code is some Flex components that make up the user interface. There are some buttons ?? Left arrow and right arrow ?? To switch to the next or previous video. There is a video list on the right side of VideoDisplay. the list only lists the video names.
Use Flex to compile and run the program. Result 4:
The first version of the. Flex User interface Now we can use the list on the right to select a video, or press the left/right button to switch between videos. This program is already quite good, but where can we use thumbnails?
Flex interface, part 2 ?? Thumbnail added
To use thumbnails in the list, you need to make changes to the list so that the thumbnail and its title can be displayed at the same time. Fortunately, it is easy to implement this in Flex. First, we need to modify Tag to add an itemRenderer. the code is as follows:
Copy the content of mytube2.mxml to the clipboard code:
...
DataProvider = "{movies }"
Change = "onChange ()"
ItemRenderer = "MovieItem">
...
The itemRenderer is an MXML component created by you, and its file name must be MovieItem. You can create a file by selecting New> MXML Component in the menu, and then add the following code:
MovieItem. mxml:
Height = "{data. height/3}" rotation = "5" left = "10" top = "0"/>
I used the Canvas container so that I can locate the components according to my own ideas. of course, you can use the container that best fits your layout. Then, I used Labels are used to load images and use Label to display the title. To make it look interesting, we rotate the image slightly. See the final results.
. Use the thumbnail enhanced list box
Well, although the appearance is not very good, it is much cooler than the simple text list. Next, you can add more things you want in this component, such as the video description, running time, link, and score button.
Storage and bandwidth
Although it is relatively easy to set up front-end programs and database operations, this is not the only problem facing the establishment of a video sharing website. Currently, bandwidth is the main problem. These videos, even in a Compact Flash Video format, are quite large files. It is worth considering how to provide video services without exhausting bandwidth.
Of course, one way to solve bandwidth is to buy a larger connection or place the host in a data center with better bandwidth conditions. Another option is to separate websites from data and store video files elsewhere. Amazon's S3 service provides a simple way to store and share large files in a surplus and upgradeable manner as long as you pay a considerable amount of money. Early use of S3 to store video files on the website can help you save a lot of infrastructure costs, and you can always use the website to pay for infrastructure costs if it is popular enough.
Summary
With the emergence of Flash Video and the widespread popularity of broadband, it is no longer a fantasy to build a Video sharing website at a very small cost. I hope this example will show you how easy it is to create a video sharing website using Flex/PHP and inspire your further exploration. |