黑马程序员技术交流社区

标题: 【太原校区】实时视屏播放的简单实现 [打印本页]

作者: 郝永亮    时间: 2019-1-23 21:59
标题: 【太原校区】实时视屏播放的简单实现
本帖最后由 郝永亮 于 2019-1-23 22:01 编辑

实时视屏播放的简单实现
通过使用nginx搭建一个简单的服务器,使用ffmpeg推送rtmp实时流,利用video标签实现可以在web端和手机端的浏览器中进行直播。
Windows下面搭建基于rtmp的服务器硬件环境
操作系统:windows7旗舰版
处 理 器:Intel(R) Core(TM)i5-5200 CPU @2.20GHz 2.20 GHz
系统内存: 8GB
系统类型:64位操作系统
软件环境及配置
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
server {
    listen       80;
    # server_name  localhost;
    location /stat {
    #        rtmp_stat all;
    #        rtmp_stat_stylesheet stat.xls;
    #}
    #location /stat.xls {
    #        root nginx-rtmp-module/;
    #}
    #location /control {
    #        rtmp_control all;
    #}
    location /hls {  
        # Serve HLS fragments  
        types {  
            application/vnd.apple.mpegurl m3u8;  
            video/mp2t ts;  
        }  
        root html;  
        expires -1;  
    }
在nginx.exe所在的文件夹,按住shift+右键,选中在此处打开命令窗口,进入windows的cmd。输入以下命令启动nginx服务:
1
nginx.exe -c conf\nginx-win-.conf
. 启动结果
ubuntu搭建推流服务器Nginx+rtmp
提供rtmp直播源
在搭建好基于rtmp的服务器之后,需要提供rtmp直播源。这里我们使用的香港卫视的rtmp直播源。根据nginx.conf中的hls_path配置,下面这个命令会向本地的D:\Program Files\nginx-1.7.11.3-Gryphon\html\hls下面写入ts片段和m3u8文件。
1
ffmpeg -re -analyzeduration 8000 -probesize 200000 -i "rtmp://live.hkstv.hk.lxdns.com/live/hks" -strict -2 -bsf:a aac_adtstoasc -c copy -flvflags aac_seq_header_detect -f flv rtmp://localhost/hls/mystream
[size=1em]注意
1、这里提供rtmp源的机器不一定和nginx在同一台物理主机上,可以是网络上的另一台机器,只要保证它能与nginx所在的主机建立tcp链接即可。(也就是nginx主机需要开启rtmp服务的监听端口,这里是1935,当然你也可以修改为其他的端口。)
2、ffmpeg下载地址
在网页中展示视屏
在nginx-1.7.11.3-Gryphon/html目录下面创建一个live.html。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<html>
<head>
    <link rel="stylesheet" href="http://vjs.zencdn.net/5.10/video-js.css">
</head>
    <video id=example-video width=960 height=540 class="video-js vjs-default-skin" controls autoplay=true>
        <source src="hls/mystream.m3u8" type="application/x-mpegURL">
    </video>
    <script src="http://vjs.zencdn.net/5.10/video.js"></script>
           <script src="https://cdn.bootcss.com/videojs-contrib-hls/5.14.1/videojs-contrib-hls.min.js"></script>
   </script>
    <script>
        var player = videojs('example-video');
        player.play();
    </script>
</html>
如果只是用video标签是无法播放.m3u8的视屏文件的,需要引入videojs-contrib-hls.js。videojs-contrib-hls支持一堆HLS功能,详情参考[
手机端如果与web可以在同一个网络环境中,那么输入对应本机ip地址也是可以查看的,并且支持横屏、竖屏的切换。
其他





欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2