如果想让Flex播放视频,必须向Flex程序提供视频列表。最简便的方法就是通过XML。所以,现在我们要返回PHP部分,编写一个可以将数据库中的视频列表抽取到XML文件的页面。movies.php就实现了这个功能,代码如下:
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="<?php echo( $moviebase.$row[2] ) ?>" width="<?php echo( $row[3] ) ?>"
height="<?php echo( $row[4] ) ?>" />
}
?>
可以通过命令行运行它,然后查看生成的XML,也可以在浏览器中打开这个页面,然后你就可以看到以树形方式显示的XML,如图33.2所示。
图33.2 视频的XML列表
有了这个XML列表,我们就可以创建一个扩展自simplemovie.mxml的Flex程序,代码如下:
mytube1.mxml
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">
明显的变化就是页面上半部分添加了很多ActionScript代码,它们用来管理界面。这些代码首先在onGetMovies()中使用 HTTPService从movies.php中读取XML。当HTTPService类检测到XML时会立刻返回一个XML文档对象模型(DOM),然后我们就可以使用这个DOM来读取第一个视频并播放它。函数onGetMovies()还设定了一个movies变量来存储列表框中要显示的视频。 ActionScript代码中的其他方法处理界面可能触发不同事件,例如用户单击了视频列表、单击了“上一个”或“下一个”按钮等。
最下面的代码是一些组成用户界面的Flex组件。其中有一些按钮——左箭头和右箭头——用来切换到下一个或上一个视频。在VideoDisplay的右边有一个视频列表,在这里该列表只是列出了视频的名字。
使用Flex编译并运行程序,结果如图33.3所示。
图33.3 Flex用户界面的第一个版本
现在我们可以使用右边的列表来选择视频,或者通过按下左/右按钮在视频之间切换。这个程序已经相当不错了,不过我们的缩略图在哪里使用了呢?