Todos os produtos
Search
Central de documentação

Object Storage Service:Ingestão de stream RTMP

Última atualização: Jul 03, 2026

O Object Storage Service (OSS) permite ingerir streams de vídeo codificados em H.264 e de áudio codificados em AAC pelo protocolo Real-Time Messaging Protocol (RTMP). Você pode usar os dados de áudio e vídeo ingeridos para vídeo sob demanda ou transmissão ao vivo. Este tópico descreve como ingerir streams de áudio e vídeo no OSS e como reproduzir os dados ingeridos.

Limitações

  • O OSS oferece suporte apenas à ingestão de stream RTMP. O pull de stream não é compatível.

  • Os dados ingeridos devem conter um stream de vídeo no formato H.264.

  • O stream de áudio é opcional. Se incluído, deve estar no formato AAC; streams em outros formatos são descartados.

  • O dumping oferece suporte apenas ao protocolo HTTP Live Streaming (HLS).

  • Apenas um cliente pode ingerir um stream em um LiveChannel por vez.

Ingerir dados de áudio e vídeo no OSS

  1. Obtenha uma URL de ingestão.

    Use um SDK para chamar a operação de API PutLiveChannel, crie um LiveChannel e obter a URL de ingestão correspondente.

    • Se a lista de controle de acesso (ACL) do bucket for public-read-write, use diretamente a URL de ingestão obtida.

    • Caso a ACL do bucket seja public-read ou private, assine a URL. Para mais informações, consulte Signature V1.

    Somente os SDKs Java e Python oferecem suporte à obtenção de URLs de ingestão.

    Java

    import com.aliyun.oss.ClientException;
    import com.aliyun.oss.OSS;
    import com.aliyun.oss.OSSClientBuilder;
    import com.aliyun.oss.OSSException;
    import com.aliyun.oss.model.*;
    import java.util.List;
    import com.aliyun.oss.common.auth.*;
    import com.aliyun.oss.ClientBuilderConfiguration;
    import com.aliyun.oss.common.comm.SignVersion;
    public class Demo {
        public static void main(String[] args) throws Exception {
            String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
            // Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
            EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
            // Specify the bucket name. For example, examplebucket.
            String bucketName = "examplebucket";
            // Specify the LiveChannel name.
            String liveChannelName = "yourLiveChannelName";
            // Specify the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou.
            String region = "cn-hangzhou";
            // Create an OSSClient instance.
            // When the OSSClient instance is no longer used, call the shutdown method to release its resources.
            ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
            clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
            OSS ossClient = OSSClientBuilder.create()
            .endpoint(endpoint)
            .credentialsProvider(credentialsProvider)
            .clientConfiguration(clientBuilderConfiguration)
            .region(region)               
            .build();
            try {
                CreateLiveChannelRequest request = new CreateLiveChannelRequest(bucketName,
                        liveChannelName, "desc", LiveChannelStatus.Enabled, new LiveChannelTarget());
                CreateLiveChannelResult result = ossClient.createLiveChannel(request);
                // Obtain the ingest URLs.
                List<String> publishUrls = result.getPublishUrls();
                for (String item : publishUrls) {
                    // Obtain the ingest URL that does not contain signature information.
                    System.out.println(item);
                    // Obtain the ingest URL that contains signature information.
                    LiveChannelInfo liveChannelInfo = ossClient.getLiveChannelInfo(bucketName, liveChannelName);
                    // The expires parameter specifies the expiration time as a Unix timestamp. This example sets the expiration time to one hour from the current time.
                    long expires = System.currentTimeMillis() / 1000 + 3600;
                    // The playlistName parameter specifies the name that you passed when you called the createLiveChannel operation. If you do not specify this parameter, the default value playlist.m3u8 is used. You can also call the getLiveChannelInfo operation to obtain this name.
                    String signRtmpUrl = ossClient.generateRtmpUri(bucketName, liveChannelName, liveChannelInfo.getTarget().getPlaylistName(), expires);
                    System.out.println(signRtmpUrl);
                }
                // Obtain the playback URLs.
                List<String> playUrls = result.getPlayUrls();
                for (String item : playUrls) {
                    System.out.println(item);
                }
            } catch (OSSException oe) {
                oe.printStackTrace();
                System.out.println("Caught an OSSException, which means your request made it to OSS, "
                        + "but was rejected with an error response for some reason.");
                System.out.println("Error Message:" + oe.getErrorMessage());
                System.out.println("Error Code:" + oe.getErrorCode());
                System.out.println("Request ID:" + oe.getRequestId());
                System.out.println("Host ID:" + oe.getHostId());
            } catch (ClientException ce) {
                System.out.println("Caught an ClientException, which means the client encountered "
                        + "a serious internal problem while trying to communicate with OSS, "
                        + "such as not being able to access the network.");
                System.out.println("Error Message:" + ce.getMessage());
            } finally {
                if (ossClient != null) {
                    ossClient.shutdown();
                }
            }
        }
    }

    As URLs de ingestão retornadas são as seguintes:

    rtmp://examplebucket.oss-cn-hangzhou.aliyuncs.com/live/test-channel
    rtmp://examplebucket.oss-cn-hangzhou.aliyuncs.com/live/test-channel?Expires=1688542428&OSSAccessKeyId=LTAI********&Signature=VfUgZt5N%2B6Uk4C9QH%2BzrRBTO2I****&playlistName=playlist.m3u8
    http://examplebucket.oss-cn-hangzhou.aliyuncs.com/test-channel/playlist.m3u8

    Python

    # -*- coding: utf-8 -*-
    import oss2
    from oss2.credentials import EnvironmentVariableCredentialsProvider
    # Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
    auth = oss2.ProviderAuth(EnvironmentVariableCredentialsProvider())
    # Specify the endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
    # Specify the bucket name. For example, examplebucket.
    bucket = oss2.Bucket(auth, 'https://oss-cn-hangzhou.aliyuncs.com', 'examplebucket')
    # Specify the LiveChannel name. For example, test-channel.
    channel_name = "test-channel"
    channel_cfg = oss2.models.LiveChannelInfo(target = oss2.models.LiveChannelInfoTarget())
    channel = bucket.create_live_channel(channel_name, channel_cfg)
    publish_url = channel.publish_url
    # Generate a signed URL for RTMP stream ingest and set the expiration time to 3,600 seconds.
    signed_publish_url = bucket.sign_rtmp_url(channel_name, "playlist.m3u8", 3600)
    # Print the unsigned ingest URL.
    print('publish_url='+publish_url)
    # Print the signed ingest URL.
    print('signed_publish_url='+signed_publish_url)

    As URLs de ingestão retornadas são as seguintes:

    publish_url=rtmp://examplebucket.oss-cn-hangzhou.aliyuncs.com/live/test-channel
    signed_publish_url=rtmp://examplebucket.oss-cn-hangzhou.aliyuncs.com/live/test-channel?playlistName=playlist.m3u8&OSSAccessKeyId=LTAI********&Expires=1688543369&Signature=eqK8z0ZTSwznP7fkELy0ckt0Iv****
  2. Use a URL de ingestão para enviar dados de áudio e vídeo ao OSS.

    A convenção de nomenclatura dos arquivos gerados pela ingestão de stream é <channel-name><timestamp>.ts, em que <channel-name> representa o nome do canal e <timestamp> indica o timestamp em milissegundos da geração do fragmento de arquivo.

    FFmpeg

    Use o FFmpeg para ingerir um arquivo de vídeo local no OSS. Exemplo:

    ffmpeg -i 1.flv -c copy -f flv "rtmp://examplebucket.oss-cn-hangzhou.aliyuncs.com/live/test-channel?playlistName=playlist.m3u8&OSSAccessKeyId=LTAI********&Expires=1688543369&Signature=eqK8z0ZTSwznP7fkELy0ck***"

    OBS

    1. Instale o OBS Studio.

    2. Na barra de navegação superior, escolha .

    3. No painel de navegação à esquerda, clique em Stream.

    4. Configure os seguintes parâmetros na caixa de diálogo:

      Parâmetro

      Descrição

      Service

      Na lista suspensa, selecione Custom.

      Server

      Insira a URL da Etapa 1 sem as informações de assinatura de ingestão de stream: rtmp://examplebucket.oss-cn-hangzhou.aliyuncs.com/live.

      Stream Key

      Insira as informações assinadas de ingestão de stream obtidas na Etapa 1: test-channel?playlistName=playlist.m3u8&OSSAccessKeyId=LTAI**************&Expires=1688543369&Signature=eqK8z0ZTSwznP7fkELy0ck********.

    5. Clique em OK.

Reproduzir áudio e vídeo ingeridos

Live streaming

Durante a ingestão de stream, reproduza o conteúdo pelo protocolo HLS. O método de reprodução varia conforme a plataforma:

  • Em plataformas móveis como Android e iOS, abra a URL de reprodução do LiveChannel em um navegador web.

  • No macOS, use o navegador Safari para reprodução.

  • Em um PC, instale o VLC media player. Após a instalação, abra o VLC media player, escolha e insira a URL de reprodução obtida na caixa de texto Please Enter A Network URL.

Para garantir uma transmissão ao vivo fluida, defina um FragDuration curto (por exemplo, 2 segundos) e um tamanho de Group of Pictures (GOP) correspondente. No OBS, essa configuração chama-se Keyframe Interval.

No OBS, acesse Settings > Output. Defina Output Mode como Advanced. Na aba Streaming, configure Keyframe Interval (seconds, 0=auto) para 2.

Video-on-demand

Durante a ingestão de stream, o OSS envia ou atualiza continuamente o arquivo M3U8 como um stream ao vivo. Ao término da ingestão, chame a operação de API PostVodPlaylist para criar uma playlist de VOD. Use a URL dessa playlist para reprodução.

Para cenários de vídeo sob demanda, configure um GOP maior para reduzir a quantidade de arquivos .ts e diminuir a taxa de bits.

Documentos relacionados