生成直播地址

发起一场直播需要生成一个推流地址用于主播的直播推流,和一个播流地址用于分发给观众进行播放。本文档介绍如何为阿里云视频直播服务生成带鉴权的推流地址和播流地址,以实现安全、可靠的直播流分发。

前提条件

在生成推/播流地址前,您需要完成推/播流域名的添加,并进行推/播流域名关联,详细操作请参见添加推流域名和播流域名

说明

每个域名可生成多个推流和播放地址,支持多场直播并发。推流域名的并发推流上限:北京、上海、深圳为300路,其他直播中心为50路,详情请参见使用限制

生成规则

直播地址由协议推流/播流域名AppNameStreamName鉴权串组成。

image

直播地址参数说明如下表所示。

参数

说明

举例

协议

直播采用的播放协议

rtmp

推流/播流域名

已添加的域名,生成推流地址时使用推流域名,生成播流地址时使用播流域名。

example.aliyundoc.com

AppName

直播的应用名称,由用户自定义,用于区分不同的直播应用或业务场景。

liveApp

StreamName

直播的流名称,由用户自定义,用于作为直播流的唯一标识。

liveStream

鉴权串

是基于推/播流域名配置的鉴权 Key,通过 MD5 算法生成的加密字符串,用于保障直播安全,生成规则请参见推/播流地址鉴权

1763451219-0-0-c9139**********08dcaf1dad8381

地址生成

您可以根据需要选择以下任一方式生成推流和播流地址:

  1. 控制台生成:适用于初次体验和测试场景,一键生成,地址会自动附带加密的{鉴权串}

  2. 代码拼接生成:适用于生产环境。在服务端实现地址生成的自动化,便于您对直播地址进行灵活的管理和分发。

控制台生成

  1. 进入直播地址生成器页面。

  2. 完成以下配置获取推流地址和播放地址,点击开始生成,即可获取推/播流地址。

    image

    说明

    直播地址生成器暂不支持生成实时字幕播放地址

代码拼接生成

1.拼接URI

拼接规则为{协议}://{直播域名}/{AppName}/{streamName},各种协议示例请参考推流地址示例播流地址示例

// 伪代码
protocol = "rtmp"
domain = "example.aliyundoc.com"
appName = "liveApp"
streamName = "liveStream"
uri = protocol + "://" + domain + "/" + appName + "/" + streamName
// 结果: rtmp://example.aliyundoc.com/liveApp/liveStream

2.获取鉴权Key

鉴权Key用于生成鉴权串,您可以通过控制台URL鉴权配置或调用DescribeLiveDomainConfigs - 查询直播域名配置API获取鉴权Key。

说明

推流地址使用推流域名的鉴权Key,播放地址使用播流域名的鉴权Key。

3.拼接为直播地址

以下示例代码以RTMP协议为例,先生成{鉴权串},再拼接出完整的直播地址:

Java

import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class AuthDemo {
    private static String md5Sum(String src) {
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        md5.update(StandardCharsets.UTF_8.encode(src));
        return String.format("%032x", new BigInteger(1, md5.digest()));
    }

private static String aAuth(String uri, String key, long exp) {
    String pattern = "^(rtmp://)?([^/?]+)(/[^?]*)?(\\\\?.*)?$";
    Pattern r = Pattern.compile(pattern);
    Matcher m = r.matcher(uri);
    String scheme = "", host = "", path = "", args = "";
    if (m.find()) {
        scheme = m.group(1) == null ? "rtmp://" : m.group(1);
        host = m.group(2) == null ? "" : m.group(2);
        path = m.group(3) == null ? "/" : m.group(3);
        args = m.group(4) == null ? "" : m.group(4);
    } else {
        System.out.println("NO MATCH");
    }

    String rand = "0";  // "0" by default, other value is ok
    String uid = "0";   // "0" by default, other value is ok
    String sString = String.format("%s-%s-%s-%s-%s", path, exp, rand, uid, key);
    String hashValue = md5Sum(sString);
    String authKey = String.format("%s-%s-%s-%s", exp, rand, uid, hashValue);
    if (args.isEmpty()) {
        return String.format("%s%s%s%s?auth_key=%s", scheme, host, path, args, authKey);
    } else {
        return String.format("%s%s%s%s&auth_key=%s", scheme, host, path, args, authKey);
    }
}

public static void main(String[] args) {
    // 待加密的推/播流地址,example.aliyundoc.com为推/播流域名,liveApp为AppName,liveStream为StreamName
    // 推流和播流URL采用同样的加密方法
    // AppName或StreamName不超过256字符,支持数字、大小写字母、短划线(-)、下划线(_)、等号(=)。
    String uri = "rtmp://example.aliyundoc.com/liveApp/liveStream";  
    // 鉴权Key,推流地址使用推流域名URL鉴权Key,播流地址使用播流域名URL鉴权Key
    String key = "<input private key>";                       
    // exp值为UNIX时间戳,单位秒,最终失效时间由该值加上域名URL鉴权有效时长决定
    // 比如您在此处设置exp为:当前时间+3600秒,那最终失效时间为:当前时间+3600秒+域名URL鉴权有效时长。如果设置exp为:当前时间,那最终失效时间为:当前时间+域名URL鉴权有效时长
    long exp = System.currentTimeMillis() / 1000 + 1 * 3600;  
    String authUri = aAuth(uri, key, exp);                    
    System.out.printf("URL : %s\nAuth: %s", uri, authUri);
}
}

Python

import re
import time
import hashlib
import datetime
def md5sum(src):
    m = hashlib.md5()
    m.update(src)
    return m.hexdigest()
def a_auth(uri, key, exp):
    p = re.compile("^(rtmp://)?([^/?]+)(/[^?]*)?(\\?.*)?$")
    if not p:
        return None
    m = p.match(uri)
    scheme, host, path, args = m.groups()
    if not scheme: scheme = "rtmp://"
    if not path: path = "/"
    if not args: args = ""
    rand = "0"      # "0" by default, other value is ok
    uid = "0"       # "0" by default, other value is ok
    sstring = "%s-%s-%s-%s-%s" %(path, exp, rand, uid, key)
    hashvalue = md5sum(sstring.encode('utf-8'))
    auth_key = "%s-%s-%s-%s" %(exp, rand, uid, hashvalue)
    if args:
        return "%s%s%s%s&auth_key=%s" %(scheme, host, path, args, auth_key)
    else:
        return "%s%s%s%s?auth_key=%s" %(scheme, host, path, args, auth_key)
def main():
    # 待加密的推/播流地址,example.aliyundoc.com为推/播流域名,liveApp为AppName,liveStream为StreamName
    # 推流和播流URL采用同样的加密方法
    # AppName或StreamName不超过256字符,支持数字、大小写字母、短划线(-)、下划线(_)、等号(=)。
    uri = "rtmp://example.aliyundoc.com/liveApp/liveStream"  
    # 鉴权Key,推流地址使用推流域名URL鉴权Key,播流地址使用播流域名URL鉴权Key
    key = "<input private key>"                         
    # exp值为UNIX时间戳,单位秒,最终失效时间由该值加上域名URL鉴权有效时长决定
    # 比如您在此处设置exp为:当前时间+3600秒,那最终失效时间为:当前时间+3600秒+域名URL鉴权有效时长。如果设置exp为:当前时间,那最终失效时间为:当前时间+域名URL鉴权有效时长
    exp = int(time.time()) + 1 * 3600                   
    authuri = a_auth(uri, key, exp)                     
    print("URL : %s\nAUTH: %s" %(uri, authuri))
if __name__ == "__main__":
    main()

Go

package main
import (
    "crypto/md5"
    "encoding/hex"
    "fmt"
    "regexp"
    "time"
)

func md5sum(src string) string {
    h := md5.New()
    h.Write([]byte(src))
    return hex.EncodeToString(h.Sum(nil))
}

func a_auth(uri, key string, exp int64) string {
    p, err := regexp.Compile("^(rtmp://)?([^/?]+)(/[^?]*)?(\\?.*)?$")
    if err != nil {
        fmt.Println(err)
        return ""
    }
    m := p.FindStringSubmatch(uri)
    var scheme, host, path, args string
    if len(m) == 5 {
        scheme, host, path, args = m[1], m[2], m[3], m[4]
    } else {
        scheme, host, path, args = "rtmp://", "", "/", ""
    }
    rand := "0" // "0" by default, other value is ok
    uid := "0"  // "0" by default, other value is ok
    sstring := fmt.Sprintf("%s-%d-%s-%s-%s", path, exp, rand, uid, key)
    hashvalue := md5sum(sstring)
    auth_key := fmt.Sprintf("%d-%s-%s-%s", exp, rand, uid, hashvalue)
    if len(args) != 0 {
        return fmt.Sprintf("%s%s%s%s&auth_key=%s", scheme, host, path, args, auth_key)
    } else {
        return fmt.Sprintf("%s%s%s%s?auth_key=%s", scheme, host, path, args, auth_key)
    }
}

func main() {
    // 待加密的推/播流地址,example.aliyundoc.com为推/播流域名,liveApp为AppName,liveStream为StreamName
    // 推流和播流URL采用同样的加密方法
    // AppName或StreamName不超过256字符,支持数字、大小写字母、短划线(-)、下划线(_)、等号(=)。
    uri := "rtmp://example.aliyundoc.com/liveApp/liveStream" 
    // 鉴权Key,推流地址使用推流域名URL鉴权Key,播流地址使用播流域名URL鉴权Key
    key := "<input private key>"     
    // exp值为UNIX时间戳,单位秒,最终失效时间由该值加上域名URL鉴权有效时长决定
    // 比如您在此处设置exp为:当前时间+3600秒,那最终失效时间为:当前时间+3600秒+域名URL鉴权有效时长。如果设置exp为:当前时间,那最终失效时间为:当前时间+域名URL鉴权有效时长   
    exp := time.Now().Unix() + 3600                                    
    authuri := a_auth(uri, key, exp)                                       
    fmt.Printf("URL : %s\nAUTH: %s", uri, authuri)
}

PHP

<?php
function a_auth($uri, $key, $exp) {
    preg_match("/^(rtmp:\/\/)?([^\/?]+)?(\/[^?]*)?(\\?.*)?$/", $uri, $matches);
    $scheme = $matches[1];
    $host = $matches[2];
    $path = $matches[3];
    $args = $matches[4];
    if  (empty($args)) {
        $args ="";
    }
    if  (empty($scheme)) {
        $scheme ="rtmp://";
    }
    if  (empty($path)) {
        $path ="/";
    }
    $rand = "0";
    // "0" by default, other value is ok
    $uid = "0";
    // "0" by default, other value is ok
    $sstring = sprintf("%s-%u-%s-%s-%s", $path, $exp, $rand, $uid, $key);
    $hashvalue = md5($sstring);
    $auth_key = sprintf("%u-%s-%s-%s", $exp, $rand, $uid, $hashvalue);
    if ($args) {
        return sprintf("%s%s%s%s&auth_key=%s", $scheme, $host, $path, $args, $auth_key);
    } else {
        return sprintf("%s%s%s%s?auth_key=%s", $scheme, $host, $path, $args, $auth_key);
    }
}
// 待加密的推/播流地址,example.aliyundoc.com为推/播流域名,liveApp为AppName,liveStream为StreamName
// 推流和播流URL采用同样的加密方法
// AppName或StreamName不超过256字符,支持数字、大小写字母、短划线(-)、下划线(_)、等号(=)。
$uri = "rtmp://example.aliyundoc.com/liveApp/liveStream";
// 鉴权Key,推流地址使用推流域名URL鉴权Key,播流地址使用播流域名URL鉴权Key
$key = "<input private key>";
// exp值为UNIX时间戳,单位秒,最终失效时间由该值加上域名URL鉴权有效时长决定
// 比如您在此处设置exp为:当前时间+3600秒,那最终失效时间为:当前时间+3600秒+域名URL鉴权有效时长。如果设置exp为:当前时间,那最终失效时间为:当前时间+域名URL鉴权有效时长
$exp = time() + 3600;
$authuri = a_auth($uri, $key, $exp);
echo "URL :" . $uri;
echo PHP_EOL;
echo "AUTH:" . $authuri;
?>

C#

using System;
using System.Text.RegularExpressions;
using System.Security.Cryptography;
using System.Text;
public class Test
{
    public static void Main()
    {
        // 待加密的推/播流地址,example.aliyundoc.com为推/播流域名,liveApp为AppName,liveStream为StreamName
        // 推流和播流URL采用同样的加密方法
        // AppName或StreamName不超过256字符,支持数字、大小写字母、短划线(-)、下划线(_)、等号(=)。
        string uri= "rtmp://example.aliyundoc.com/liveApp/liveStream";  
        // 鉴权Key,推流地址使用推流域名URL鉴权Key,播流地址使用播流域名URL鉴权Key
        string key= "<input private key>";                           
        DateTime dateStart = new DateTime(1970, 1, 1, 8, 0, 0);
        // exp值为UNIX时间戳,单位秒,最终失效时间由该值加上域名URL鉴权有效时长决定
        // 比如您在此处设置exp为:当前时间+3600秒,那最终失效时间为:当前时间+3600秒+域名URL鉴权有效时长。如果设置exp为:当前时间,那最终失效时间为:当前时间+域名URL鉴权有效时长
        string exp  = Convert.ToInt64((DateTime.Now - dateStart).TotalSeconds+3600).ToString(); 
        string authUri = aAuth(uri, key, exp);
        Console.WriteLine (String.Format("URL :{0}",uri));
        Console.WriteLine (String.Format("AUTH :{0}",authUri));
    }
    public static string aAuth(string uri, string key, string exp)
    {
        Regex regex = new Regex("^(rtmp://)?([^/?]+)(/[^?]*)?(\\\\?.*)?$");
        Match m = regex.Match(uri);
        string scheme = "rtmp://", host = "", path = "/", args = "";
        if (m.Success)
        {
            scheme=m.Groups[1].Value;
            host=m.Groups[2].Value;
            path=m.Groups[3].Value;
            args=m.Groups[4].Value;
        }else{
            Console.WriteLine ("NO MATCH");
        }
        string rand = "0";  // "0" by default, other value is ok
        string uid = "0";   // "0" by default, other value is ok
        string u = String.Format("{0}-{1}-{2}-{3}-{4}",  path, exp, rand, uid, key);
        string hashValue  = Md5(u);
        string authKey = String.Format("{0}-{1}-{2}-{3}", exp, rand, uid, hashValue);
        if (args=="")
        {
            return String.Format("{0}{1}{2}{3}?auth_key={4}", scheme, host, path, args, authKey);
        } else
        {
            return String.Format("{0}{1}{2}{3}&auth_key={4}", scheme, host, path, args, authKey);
        }
    }
    public static string Md5(string value)
    {
        MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
        byte[] bytes = Encoding.ASCII.GetBytes(value);
        byte[] encoded = md5.ComputeHash(bytes);
        StringBuilder sb = new StringBuilder();
        for(int i=0; i<encoded.Length; ++i)
        {
            sb.Append(encoded[i].ToString("x2"));
        }
        return sb.ToString();
   }
}

推流地址示例

支持协议

地址示例

说明

RTMP

rtmp://{域名}/{AppName}/{StreamName}?auth_key={鉴权串}

标准直播推流协议。

ARTC

artc://{域名}/{AppName}/{StreamName}?auth_key={鉴权串}

阿里云超低延时直播RTS推流地址。

SRT

srt://{域名}:1105?streamid=#!::h={域名},r=/{AppName}/{StreamName}?auth_key={鉴权串},m=publish

SRT协议默认关闭,需为推流域名开启SRT协议后方可使用,操作指引参见SRT推流

播流地址示例

播流地址

说明

支持协议

地址示例

标准直播播流地址

推流为SRT协议时,播流协议支持RTMP、FLV、HLS、ARTC。

RTMP

rtmp://{域名}/{AppName}/{StreamName}?auth_key={鉴权串}

FLV

http://{域名}/{AppName}/{StreamName}.flv?auth_key={鉴权串}

HLS

http://{域名}/{AppName}/{StreamName}.m3u8?auth_key={鉴权串}

ARTC

artc://{域名}/{AppName}/{StreamName}?auth_key={鉴权串}

转码流播流地址(通用转码/自定义转码

转码流地址需要在StreamName后加_转码模板ID转码模板ID需通过直播转码功能进行配置。

RTMP

rtmp://{域名}/{AppName}/{StreamName}_{转码模板ID}?auth_key={鉴权串}

FLV

http://{域名}/{AppName}/{StreamName}_{转码模板ID}.flv?auth_key={鉴权串}

HLS

http://{域名}/{AppName}/{StreamName}_{转码模板ID}.m3u8?auth_key={鉴权串}

ARTC

artc://{域名}/{AppName}/{StreamName}_{转码模板ID}?auth_key={鉴权串}

转码流播流地址(多码率转码

多码率转码流地址需要在StreamName后加_转码模板组ID,地址中需增加aliyunols=on参数,转码模板组ID需通过直播转码功能进行配置。

HLS

http://{域名}/{AppName}/{StreamName}_{转码模板组ID}.m3u8?aliyunols=on&auth_key={鉴权串}

延播播流地址

延播播流地址需要在StreamName后加-alidelay。使用延播播流前需进行延播配置

RTMP

rtmp://{域名}/{AppName}/{StreamName}-alidelay?auth_key={鉴权串}

FLV

http://{域名}/{AppName}/{StreamName}-alidelay.flv?auth_key={鉴权串}

HLS

http://{域名}/{AppName}/{StreamName}-alidelay.m3u8?auth_key={鉴权串}

ARTC

artc://{域名}/{AppName}/{StreamName}-alidelay?auth_key={鉴权串}

实时字幕播流地址

实时字幕播流地址需要在StreamName后加_字幕模板名称字幕模板名称需通过实时字幕功能进行配置。

RTMP

rtmp://{域名}/{AppName}/{StreamName}_{字幕模板名称}?auth_key={鉴权串}

FLV

http://{域名}/{AppName}/{StreamName}_{字幕模板名称}.flv?auth_key={鉴权串}

HLS

http://{域名}/{AppName}/{StreamName}_{字幕模板名称}.m3u8?auth_key={鉴权串}

生成地址验证

本文推荐使用手机端Demo APP推流,和PCVLC播放器播流完成生成地址有效性验证,更多推/播流方式请参见直播推流直播播流

推流地址验证:

  1. 准备好一台手机,安卓系统或者iOS系统均可。扫描并安装阿里云直播应用Demo。

    image

    说明

    iOS端扫码安装时如果提示未受信任的企业级开发者,需要在设置 > 通用 > 设备管理中找到Taobao对应的信任描述,并选择信任。

  2. 打开Demo App,选择摄像头推流录屏推流。输入推流地址,控制台生成的地址可使用二维码扫描输入。

    imageimage

  3. 点击开始推流,此时就完成了主播开播的流程。

    您可以在视频直播控制台-流管理页面,看到当前的在线流,若未看到直播流,请确认前面操作步骤是否正确。

    image

播流地址验证:

说明

在进行直播播放操作时,需保持推流端维持直播推流状态,否则播放端将会播放失败。

  1. 下载并安装VLC播放器。下载地址,请参见VLC media player

  2. 运行VLC播放器。

  3. 在菜单栏中选择媒体 > 打开网络串流

  4. 网络页签中输入网络URL,即生成的播放地址,如:rtmp://pull-singapore.cloud-example.net/testApp/testStream?auth_key=1750150177-0-0-9b7*******31acc543a99c69********

    p888206

问题排查

进行推流/播流时遇到问题可以使用自助问题排查功能对地址进行检测,验证地址,鉴权等信息是否有效。