zoukankan      html  css  js  c++  java
  • Swift搭建本地http服务器,实现外部视频即时播放

    最近项目有个小需求,需要ios实现手机作为服务端,将内部视频文件,在外面能够直接访问

    结合网上的例子,实现如下:

    1、基于CocoaHTTPServer实现

    2、可用pod集成,也可直接拖动文件集成

    pod集成:

    1、新建项目,Podfile文件如下,执行install

    pod 'CocoaHTTPServer'

    2、直接拖文件

    a、先下载文件CocoaHTTPServer,如下:

    导入CocoaHTTPServer-master目录下的Core文件夹

    导入Vendor目录下的CocoaAsyncSocketCocoaLumberjack文件夹

    3、在 ViewController里写开启代码

    a、由于是swift项目,而以上库都是基于OC的,所以需要在桥接文件import头

    b、初始化httpServer

         httpServer = HTTPServer()
            httpServer.setType("_http.tcp")        
            
            //1、播放沙盒文件
            print("(NSHomeDirectory())/Documents")
            //设置http服务器根目录
            httpServer.setDocumentRoot("(NSHomeDirectory())/Documents")

    注意:

    1、以上的根目录我是直接定位到Documents下的,这里可自行更换

    2、这里我直接拿沙盒的文件播放的,所以demo下载后,需要在沙盒里先添加一个视频,或者直接把我项目里放置的那个视频拖进去。

    c、开启、关闭。(这里我为了省事,直接点击屏幕进行控制)

     override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
            isOPen = !isOPen
            if isOPen{
                do{
                    try httpServer.start()
                    print( "请打开以下网址: http://(HTTPHelper.ipAddress() ?? ""):(httpServer.listeningPort())/1.mp4")
                }catch{
                    print("启动失败")
                }
                
            }else{
                httpServer.stop()
            }
        }

    d、开启后,注意打印的地址,拷贝到电脑的浏览器地址栏,可以直接下载,或者在vlc添加播放地址

    (vlc可以直接百度下载即可。)

    e、vlc里直接观看,当然其他播放器也可以,直接把播放地址添加下。注意:这里必须保证播放器所在局域网和手机一致。

    视频播放时,可以快进、快退、暂停等操作。

    源码下载

    写在最后:

    1、以上只是一个简单的例子,实现了ios设备做服务端,外部设备做客户端,直接访问ios设备的资源(不仅仅是视频,其他文件同理)

    2、pod集成和手动集成都是可以的,见上文

    3、本文是swift版本的,如果需要oc版本,可参考:https://github.com/OPTJoker/CocoaHttpServer

  • 相关阅读:
    ExecuteScalar requires the command to have a transaction when the connection assigned to the command is in a pending
    如何从vss中分离程序
    String or binary data would be truncated
    the pop3 service failed to retrieve authentication type and cannot continue
    The POP3 service failed to start because
    IIS Error he system cannot find the file specified _找不到页面
    pku2575Jolly Jumpers
    pku2940Wine Trading in Gergovia
    pku3219二项式系数
    pku1029false coin
  • 原文地址:https://www.cnblogs.com/yajunLi/p/8488946.html
Copyright © 2011-2022 走看看