Todos os produtos
Search
Central de documentação

ApsaraVideo Live:Integrar o SDK de sala de chat de voz no Android

Última atualização: Jun 30, 2026

Crie uma sala de chat de voz no Android com o ApsaraVideo Live ARTC SDK. Este guia aborda a criação de canais, o acesso baseado em funções, os controles de áudio e a música de fundo.

Pré-requisitos

Antes de começar, verifique se você tem:

Como funciona

A sala de chat de voz usa o ARTC SDK em modo apenas áudio com acesso baseado em funções:

  • Streamer (função interativa): crie o canal, publica áudio e recebe áudio de todos os participantes.

  • Viewer (função ao vivo): entra em um canal existente e recebe áudio. Pode ser promovido a co-streamer mediante troca de função.

Fluxo de implementação:

  1. Configure o perfil do canal e a função do cliente.

  2. Defina o perfil de áudio para música de alta qualidade.

  3. Gere e codifique o token de autenticação.

  4. Entre no canal.

Implementation diagram

Criar um canal como streamer

Inicialize o SDK no modo interativo ao vivo, defina a função interativa e entre no canal. O SDK assina automaticamente todos os fluxos de áudio remotos.

// Set channel profile to interactive live streaming
mAliRtcEngine.setChannelProfile(AliRTCSdkInteractiveLive);
// Set the role to interactive (streamer can publish and receive audio)
mAliRtcEngine.setClientRole(AliRTCSdkInteractive);
// Use high-quality music mode for voice chat scenarios
mAliRtcEngine.setAudioProfile(AliRtcEngineHighQualityMode, AliRtcSceneMusicMode);

// Set the listener for callbacks
mAliRtcEngine.setRtcEngineEventListener(this);
// Auto-publish local audio
mAliRtcEngine.publishLocalAudioStream(true);
// Auto-subscribe to all remote audio streams
mAliRtcEngine.setDefaultSubscribeAllRemoteAudioStreams(true);
mAliRtcEngine.subscribeAllRemoteAudioStreams(true);
// Enable audio-only mode (no video)
mAliRtcEngine.setAudioOnlyMode(true);

// Build the authentication token
JSONObject tokenv2 = new JSONObject();
tokenv2.put("appid", userInfo.appId);
tokenv2.put("channelid", userInfo.channelId);
tokenv2.put("userid", userInfo.userId);
tokenv2.put("nonce", userInfo.nonce);
tokenv2.put("timestamp", userInfo.timestamp);
tokenv2.put("gslb",userInfo.gslb);
tokenv2.put("token", userInfo.token);
String base64TokenV2 = Base64.encodeToString(JSON.toJSONBytes(tokenv2),Base64.NO_WRAP);
// Join the channel with the Base64-encoded token
mAliRtcEngine.joinChannel(base64TokenV2, null, null, mUsername);

Entrar em um canal como viewer

O viewer segue o mesmo fluxo de inicialização do streamer, exceto pela função do cliente, definida como AliRTCSdkLive em vez de AliRTCSdkInteractive. Isso designa o usuário como viewer comum.

Para entrar como co-streamer, defina a função como AliRTCSdkInteractive.

mAliRtcEngine.setChannelProfile(AliRTCSdkInteractiveLive);
// Set the role to live (ordinary viewer)
mAliRtcEngine.setClientRole(AliRTCSdkLive);
// Use high-quality music mode for voice chat scenarios
mAliRtcEngine.setAudioProfile(AliRtcEngineHighQualityMode, AliRtcSceneMusicMode);

// Set the listener for callbacks
mAliRtcEngine.setRtcEngineEventListener(this);
// Auto-publish local audio
mAliRtcEngine.publishLocalAudioStream(true);
// Auto-subscribe to all remote audio streams
mAliRtcEngine.setDefaultSubscribeAllRemoteAudioStreams(true);
mAliRtcEngine.subscribeAllRemoteAudioStreams(true);
// Enable audio-only mode (no video)
mAliRtcEngine.setAudioOnlyMode(true);

// Build the authentication token
JSONObject tokenv2 = new JSONObject();
tokenv2.put("appid", userInfo.appId);
tokenv2.put("channelid", userInfo.channelId);
tokenv2.put("userid", userInfo.userId);
tokenv2.put("nonce", userInfo.nonce);
tokenv2.put("timestamp", userInfo.timestamp);
tokenv2.put("gslb",userInfo.gslb);
tokenv2.put("token", userInfo.token);
String base64TokenV2 = Base64.encodeToString(JSON.toJSONBytes(tokenv2),Base64.NO_WRAP);
// Join the channel with the Base64-encoded token
mAliRtcEngine.joinChannel(base64TokenV2, null, null, mUsername);

Alternar a função do viewer

Após um viewer entrar no canal, alterne a função dinamicamente:

// Switch the role to streamer for a user who has joined the channel
mAliRtcEngine.setClientRole(AliRTCSdkInteractive);

Controlar volume, efeitos de voz e reverberação

Ajustar volume

// Adjust the local recording volume
mAliRtcEngine.setRecordingVolume(volumeLevel);
// Adjust the volume of a specific remote user
mAliRtcEngine.setRemoteAudioVolume(uid, volume);
// Adjust the playback volume of all sounds
mAliRtcEngine.setPlayoutVolume(volume);

Aplicar modificador de voz

// Apply the "old man" voice changer effect
mAliRtcEngine.setAudioEffectVoiceChangerMode(AliRtcSdk_AudioEffect_Voice_Changer_Oldman);

Aplicar reverberação

// Configure reverberation by setting room size
mAliRtcEngine.setAudioEffectReverbParamType(AliRtcEngine.AliRtcAudioEffectReverbParamType.AliRtcSdk_AudioEffect_Reverb_Room_Size, value);

Reproduzir música de fundo

Há dois métodos disponíveis: entrada de dados PCM brutos e entrada baseada em arquivo.

Entrada de dados PCM

Crie um fluxo de entrada de música e envie frames PCM brutos.

Criar o fluxo de áudio externo:

AliRtcEngine.AliRtcExternalAudioStreamConfig config = new AliRtcEngine.AliRtcExternalAudioStreamConfig();
config.sampleRate = sampleRate;
config.channels = channels;
// Local playback volume of the accompaniment (used when the ARTC SDK handles playback)
config.playoutVolume = 60;
// Volume published to remote participants
config.publishVolume = 100;
int externalAudioStreamId = aliRtcEngine.addExternalAudioStream(config);

Parâmetros de AliRtcExternalAudioStreamConfig:

Parâmetro

Descrição

sampleRate

Taxa de amostragem de áudio

channels

Número de canais de áudio

playoutVolume

Volume de reprodução local do acompanhamento

publishVolume

Volume publicado para participantes remotos

Enviar dados PCM:

// Build an audio frame with raw PCM data
AliRtcEngine.AliRtcAudioFrame sample = new AliRtcEngine.AliRtcAudioFrame();
sample.data = buffer;
sample.numSamples = numSamples;
sample.numChannels = channels;
sample.sampleRate = sampleRate;
sample.bytesPerSample = bytesPerSample;
// Push the PCM data to the external audio stream
int ret = aliRtcEngine.pushExternalAudioStreamRawData(externalAudioStreamId, sample);

Campos de AliRtcAudioFrame:

Campo

Descrição

data

Buffer de áudio PCM bruto

numSamples

Número de amostras de áudio

numChannels

Número de canais de áudio

sampleRate

Taxa de amostragem de áudio

bytesPerSample

Bytes por amostra de áudio

Entrada baseada em arquivo

Inicie o acompanhamento a partir de um arquivo de áudio local:

AliRtcEngine.AliRtcAudioAccompanyConfig config = new AliRtcEngine.AliRtcAudioAccompanyConfig();
config.onlyLocalPlay = localPlay;       // Play locally only, without publishing
config.replaceMic = replaceMic;         // Replace microphone input with the file
config.loopCycles = loopCycles;         // Number of playback loops
config.startPosMs = startPosMs;         // Start position in milliseconds
config.publishVolume = pubVolume;       // Volume published to remote participants
config.playoutVolume = playVolume;      // Local playback volume
return mAliRtcEngine.startAudioAccompany(audioFileName, config);

Parâmetros de AliRtcAudioAccompanyConfig:

Parâmetro

Descrição

onlyLocalPlay

Reproduz apenas localmente, sem publicar para participantes remotos

replaceMic

Substitui a entrada do microfone pelo arquivo de áudio

loopCycles

Número de ciclos de reprodução

startPosMs

Posição inicial em milissegundos

publishVolume

Volume publicado para participantes remotos

playoutVolume

Volume de reprodução local