全部产品

获取直播播放地址

摄像头设备接入视频型实例后,您需要实现一个HTTP Web Server供前端调用来获取播放地址。本文介绍获取直播播放地址的方法。

实现HTTP Web Server有很多方法,本文以Netty HTTP Server为例,展示获取直播播放地址的方法。您也可以根据实际情况,搭建HTTP Web Server。

前提条件

已将设备接入到视频型实例。具体操作,请参见建立设备与平台的连接

开发环境

本示例使用的开发环境如下:

操作步骤

  1. 打开IntelliJ IDEA,新建示例工程demo。

  2. 在工程demo的pom.xml文件中,添加Maven项目依赖。

    LinkVisual Java SDK的Maven依赖坐标:

    <dependency>
      <groupId>com.aliyun</groupId>
      <artifactId>aliyun-java-sdk-linkvisual</artifactId>
      <version>1.5.5</version>
    </dependency>

    阿里云Java SDK公共包Maven依赖坐标:

    <dependency>
        <groupId>com.aliyun</groupId>
        <artifactId>aliyun-java-sdk-core</artifactId>
        <version>4.1.1</version>
    </dependency>

    集成Netty框架:

    <dependency>
        <groupId>io.netty</groupId>
        <artifactId>netty-all</artifactId>
        <version>4.1.29.Final</version>
    </dependency>
  3. 在src/main/java路径下创建SampleHttpServer.java文件,然后输入如下代码。

    import com.aliyuncs.DefaultAcsClient;
    import com.aliyuncs.IAcsClient;
    import com.aliyuncs.linkvisual.model.v20180120.QueryLiveStreamingRequest;
    import com.aliyuncs.linkvisual.model.v20180120.QueryLiveStreamingResponse;
    import com.aliyuncs.profile.DefaultProfile;
    import io.netty.bootstrap.ServerBootstrap;
    import io.netty.buffer.Unpooled;
    import io.netty.channel.*;
    import io.netty.channel.nio.NioEventLoopGroup;
    import io.netty.channel.socket.SocketChannel;
    import io.netty.channel.socket.nio.NioServerSocketChannel;
    import io.netty.handler.codec.http.*;
    import com.aliyuncs.profile.IClientProfile;
    
    import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;
    
    /**
     * SampleHttpServer
     */
    public class SampleHttpServer {
    
        private static String LIVE_PATH = "/live/stream";
        private static String RESPONSE_SUCCESS_CODE = "200";
        private static IAcsClient client = null;
    
        private int port;
    
        public SampleHttpServer(int port) {
            this.port = port;
        }
    
        class HttpServerHandler extends ChannelInboundHandlerAdapter {
            @Override
            public void channelReadComplete(ChannelHandlerContext ctx) {
                ctx.flush();
            }
    
            @Override
            public void channelRead(ChannelHandlerContext ctx, Object msg) {
                if (msg instanceof HttpRequest) {
                    QueryStringDecoder decoder = new QueryStringDecoder(((HttpRequest)msg).uri());
                    if (decoder.path().equals(LIVE_PATH)) {
                        // 从HTTP请求中获取设备ID、实例ID、播放协议等参数。注:此处省略异常处理逻辑
                        String iotId = decoder.parameters().get("iotId").get(0);
                        String scheme = decoder.parameters().get("scheme").get(0);
                        String instanceId = decoder.parameters().get("instanceId").get(0);
    
                        // 获取播放地址接口调用
                        QueryLiveStreamingRequest queryLiveStreamingRequest = new QueryLiveStreamingRequest();
                        queryLiveStreamingRequest.setIotId(iotId);
                        queryLiveStreamingRequest.setIotInstanceId(instanceId);
                        queryLiveStreamingRequest.setScheme(scheme);
                        
                        QueryLiveStreamingResponse queryLiveStreamingResponse = null;
                        try {
                            queryLiveStreamingResponse = client.getAcsResponse(queryLiveStreamingRequest);
                        } catch (Exception e) {
                            // 执行异常
                        }
    
                        if (queryLiveStreamingResponse != null && queryLiveStreamingResponse.getCode().equals(RESPONSE_SUCCESS_CODE)) {
                            // 返回播放地址
                            FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.OK,
                                    Unpooled.wrappedBuffer(queryLiveStreamingResponse.getData().getPath().getBytes()));
                            response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain");
                            response.headers().set(HttpHeaderNames.CONTENT_LENGTH, queryLiveStreamingResponse.getData().getPath().length());
                            response.headers().set(HttpHeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN, "*");
                            response.headers().set(HttpHeaderNames.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true");
                            ctx.write(response);
                        } else {
                            // 异常处理
                        }
                    } else {
                        FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.BAD_REQUEST,
                                Unpooled.EMPTY_BUFFER);
                        ctx.write(response);
                    }
                }
            }
        }
    
        class HttpServerInitializer extends ChannelInitializer<SocketChannel> {
            @Override
            public void initChannel(SocketChannel ch) {
                ChannelPipeline p = ch.pipeline();
                p.addLast(new HttpServerCodec());
                p.addLast(new HttpServerHandler());
            }
        }
    
        public void start() {
            EventLoopGroup bossGroup = new NioEventLoopGroup(1);
            EventLoopGroup workerGroup = new NioEventLoopGroup();
            try {
                ServerBootstrap b = new ServerBootstrap();
                b.option(ChannelOption.SO_BACKLOG, 1024);
                b.group(bossGroup, workerGroup)
                        .channel(NioServerSocketChannel.class)
                        .childHandler(new HttpServerInitializer());
                try {
                    Channel ch = b.bind(port).sync().channel();
                    ch.closeFuture().sync();
                } catch (InterruptedException e) {}
            } finally {
                bossGroup.shutdownGracefully();
                workerGroup.shutdownGracefully();
            }
        }
    
        public static void main(String[] args) {
            SampleHttpServer httpServer = new SampleHttpServer(8082);
    
            // 初始化请求客户端,accessKeyID和accessKeySecret需要修改为您的阿里云账户的AccessKey ID和AccessKey Secret
            String accessKeyID = "ak!!!";
            String accessKeySecret = "sk!!!";
            String regionId = "cn-shanghai"; //您的设备所属的地域ID,无需修改
            String domain = "linkvisual.cn-shanghai.aliyuncs.com"; //请求域名,无需修改
            String productCode = "Linkvisual"; //产品Code,无需修改
            try {
                DefaultProfile.addEndpoint(regionId, regionId, productCode, domain);
                IClientProfile profile = DefaultProfile.getProfile(regionId, accessKeyID, accessKeySecret);
    
                client = new DefaultAcsClient(profile);
            } catch (Exception e) {
    
            }
    
            // 启动HTTP服务
            httpServer.start();
        }
    }

    参照下表,修改代码中的参数值。

    参数

    示例

    说明

    accessKeyID

    LTAI4GFGQvKuqHJhFa******

    登录物联网平台控制台,将鼠标指针移至账号头像上,然后单击AccessKey管理,获取AccessKey ID和AccessKey Secret。

    说明

    如果使用RAM用户,您需授予该用户管理物联网平台的权限(AliyunIOTFullAccess),否则将连接失败。授权方法请参见授权RAM用户访问物联网平台

    accessKeySecret

    iMS8ZhCDdfJbCMeA005sieKe******

  4. 代码运行成功,即已获取直播地址并启动了HTTP Server。

后续操作

在Web端播放视频