- 安卓Android中腾讯音视频和直播 API的使用
- 前言:安卓Android中腾讯音视频和直播 API的使用,这里没有写UI,功能是放在一起的,大家使用的时候自取
- 一、修改了腾讯官方教程中没及时更新的各种问题,现行版本的正确性不错
- 二、使用步骤
- 1.在Android的gradle当中添加
- 2.添加权限,这里的权限是综合音视频和直播以及短视频的也是 自取
- 3.涉及到的各种需要申请的信息
- 4.音视频直播间 主播 讲师 主持人 端的API
- 5.音视频直播间 观众API
- 6.直播主播推流及所有相关操作API
- 7.直播观众拉流及连麦互动等操作API
- 总结
前言:安卓Android中腾讯音视频和直播 API的使用,这里没有写UI,功能是放在一起的,大家使用的时候自取
案例中所有的承载均使用TXCloudVideoView
一、修改了腾讯官方教程中没及时更新的各种问题,现行版本的正确性不错 二、使用步骤 1.在Android的gradle当中添加
代码如下(示例):
在android 标签下
ndk {
abiFilters "armeabi", "armeabi-v7a", "arm64-v8a"
}
packagingOptions {
pickFirst '**/libc++_shared.so'
doNotStrip "*/armeabi/libYTCommon.so"
doNotStrip "*/armeabi-v7a/libYTCommon.so"
doNotStrip "*/x86/libYTCommon.so"
doNotStrip "*/arm64-v8a/libYTCommon.so"
}
在dependencies标签下
//实时音视频
implementation 'com.tencent.liteav:LiteAVSDK_TRTC:latest.release'
//直播的SDK
implementation 'com.tencent.liteav:LiteAVSDK_Professional:latest.release'
//短视频的SDK
implementation 'com.tencent.liteav:LiteAVSDK_UGC:latest.release'
2.添加权限,这里的权限是综合音视频和直播以及短视频的也是 自取
代码如下(示例):
3.涉及到的各种需要申请的信息
代码如下(示例):
1:在MyApplication中
package com.wlsj2022.myapplication;
import android.app.Application;
import android.util.Log;
import com.tencent.live2.V2TXLivePremier;
import com.tencent.rtmp.TXLiveBase;
import com.tencent.rtmp.TXLiveConstants;
import com.tencent.ugc.TXUGCBase;
public class MyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
// 短视频
String ugcLicenceUrl = ""; // 填入您从控制台申请的 licence url
String ugcKey = ""; // 填入您从控制台申请的 licence key
TXUGCBase.getInstance().setLicence(this, ugcLicenceUrl, ugcKey);
//是否输出log
TXLiveBase.setConsoleEnabled(true);
//log的level
TXLiveBase.setLogLevel(TXLiveConstants.LOG_LEVEL_DEBUG);
//直播
String licenceURL = ""; // 获取到的 licence url
String licenceKey = ""; // 获取到的 licence key
// TXLiveBase.getInstance().setLicence(this, licenceURL, licenceKey);
V2TXLivePremier.setLicence(this, licenceURL, licenceKey);
V2TXLivePremier.setObserver(new V2TXLivePremier.V2TXLivePremierObserver() {
@Override
public void onLicenceLoaded(int result, String reason) {
Log.i("TAG", "onLicenceLoaded: result:" + result + ", reason:" + reason);
}
});
}
}
2:推流拉流的URL及互动连麦等操作的URL
4.音视频直播间 主播 讲师 主持人 端的API代码如下(示例):
package com.wlsj2022.myapplication;
import static com.tencent.trtc.TRTCCloudDef.TRTCRoleAnchor;
import static com.tencent.trtc.TRTCCloudDef.TRTCRoleAudience;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import com.tencent.liteav.device.TXDeviceManager;
import com.tencent.rtmp.ui.TXCloudVideoView;
import com.tencent.trtc.TRTCCloud;
import com.tencent.trtc.TRTCCloudDef;
import com.tencent.trtc.TRTCCloudListener;
//音视频直播间 主播 讲师 主持人
public class AudioVideoAnchorActivity extends AppCompatActivity {
private TRTCCloud mTRTCCloud;
private TXCloudVideoView mTXCloudVideoView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTXCloudVideoView = findViewById(R.id.tXCloudVideoView);
//设置监听
initListener();
//进入房间
initEnterRoom();
//发布音视频流
initIssueAudioVideo();
//开启屏幕分享
initScreenShare();
//订阅音视频流
initSubscriptionAudioVideo();
}
//开启屏幕分享
private void initScreenShare() {
TRTCCloudDef.TRTCVideoEncParam videoEncParam = new TRTCCloudDef.TRTCVideoEncParam();
//TODO videoEncParam
videoEncParam.videoFps = 8;
videoEncParam.minVideoBitrate = 2000;
videoEncParam.videoResolution = 1920*1080;
// 分辨率自适应
// videoEncParam.enableAdjustRes = true;
//TODO
TRTCCloudDef.TRTCScreenShareParams screenShareParams = new TRTCCloudDef.TRTCScreenShareParams();
mTRTCCloud.startScreenCapture(videoEncParam,screenShareParams);
}
//发布音视频流
private void initSubscriptionAudioVideo() {
TRTCCloudDef.TRTCVideoEncParam videoEncParam = new TRTCCloudDef.TRTCVideoEncParam();
//帧率 推荐设置为 15 FPS,这样既能保证画面足够流畅,又不会因为每秒帧数太多而拉低单幅画面的清晰度。
videoEncParam.videoFps = 15;
//码率 1300 和 质量成正比 越大 |码率不动 分辨率越低 视频看起来越清晰
videoEncParam.minVideoBitrate = 850;
//编码分辨率 | 分辨率不动 码率越大 越清晰
// TRTCCloudDef.TRTC_VIDEO_RESOLUTION_960_540;
videoEncParam.videoResolution = 540*960;
//配置一个竖屏的分辨率 TODO 是否会直接翻转
videoEncParam.videoResolutionMode = TRTCCloudDef.TRTC_VIDEO_RESOLUTION_MODE_PORTRAIT;
mTRTCCloud.setVideoEncoderParam(videoEncParam);
TRTCCloudDef.TRTCNetworkQosParam networkQosParam = new TRTCCloudDef.TRTCNetworkQosParam();
//流畅度优先 解决了弱网环境下的视频播放的问题 清晰度优先TRTCVideoQosPreferenceClear
networkQosParam.preference = TRTCCloudDef.TRTC_VIDEO_QOS_PREFERENCE_SMOOTH;
mTRTCCloud.setNetworkQosParam(networkQosParam);
//打开摄像头预览
openCameraPreview();
//打开麦克风采集
mTRTCCloud.startLocalAudio(TRTCCloudDef.TRTC_AUDIO_QUALITY_SPEECH);
//开启麦克风采集,并设置当前场景为:音乐模式(高保真采集、低音质损失,推荐配合专业声卡使用)
//mCloud.startLocalAudio(TRTCCloudDef.TRTC_AUDIO_QUALITY_MUSIC);
//点击按钮 上麦 TODO 已经指定为主播 这个时候再次切换到主播可能出现的问题
//TODO mTRTCCloud.switchRole(TRTCCloudDef.TRTCRoleAnchor);
}
//开启摄像头的预览
private void openCameraPreview() {
// 设置本地画面的预览模式:开启左右镜像,设置画面为填充模式
TRTCCloudDef.TRTCRenderParams param = new TRTCCloudDef.TRTCRenderParams();
param.fillMode = TRTCCloudDef.TRTC_VIDEO_RENDER_MODE_FILL;
param.mirrorType = TRTCCloudDef.TRTC_VIDEO_MIRROR_TYPE_AUTO;
mTRTCCloud.setLocalRenderParams(param);
// 启动本地摄像头的预览(localCameraVideo 是用于渲染本地渲染画面的控件)
mTRTCCloud.startLocalPreview(true, mTXCloudVideoView);
// 通过 TXDeviceManager 开启自动对焦并将闪光灯打开
TXDeviceManager manager = mTRTCCloud.getDeviceManager();
if (manager.isAutoFocusEnabled()) {
manager.enableCameraAutoFocus(true);
}
manager.enableCameraTorch(true);
}
//订阅音视频流
private void initIssueAudioVideo() {
// Mute user with id denny 其他用户静音
// mTRTCCloud.muteRemoteAudio("denny", true);
}
// 进入房间
private void initEnterRoom() {
// 设置美颜等级
mTRTCCloud.getBeautyManager().setBeautyLevel(100);
TRTCCloudDef.TRTCParams params = new TRTCCloudDef.TRTCParams();
//设置sdkAppId
//userID roomId
params.sdkAppId = 123;
//用户的id
params.userId = "123";
//直播间号
params.roomId = 123;
//直播间号
params.strRoomId = "";
//用户进入房间的鉴权
params.userSig = "eJyrVareCeYrSy1SslI";
//指定角色为主播
params.role = TRTCRoleAnchor;
//进入房间
//在线直播的场景 TRTCCloudDef.TRTC_APP_SCENE_LIVE
mTRTCCloud.enterRoom(params, TRTCCloudDef.TRTC_APP_SCENE_LIVE);
}
//初始化监听
private void initListener() {
// 创建 SDK 实例(单例模式)并设置事件监听器
// Create trtc instance(singleton) and set up event listeners
mTRTCCloud = TRTCCloud.sharedInstance(getApplicationContext());
mTRTCCloud.setListener(new TRTCCloudListener() {
//错误的信息
@Override
public void onError(int errCode, String errMsg, Bundle extraInfo) {
super.onError(errCode, errMsg, extraInfo);
Toast.makeText(getApplicationContext(), "由于" + errMsg + "退出直播间", Toast.LENGTH_SHORT).show();
// 退出房间 TODO 如果有错误码 就判断
mTRTCCloud.exitRoom();
}
//进入房间 如果是复数就失败
@Override
public void onEnterRoom(long result) {
if (result > 0) {
Log.d("TAG", "Enter room succeed");
} else {
Log.d("TAG", "Enter room failed");
}
}
//退出房间
@Override
public void onExitRoom(int reason) {
super.onExitRoom(reason);
}
//链接断了
@Override
public void onConnectionLost() {
super.onConnectionLost();
}
//切换主播失败
@Override
public void onSwitchRoom(int errCode, String errMsg) {
if (errCode != 0) {
Log.d("TAG", "Switching operation failed...");
}
}
});
}
}
5.音视频直播间 观众API
代码如下(示例):
package com.wlsj2022.myapplication;
import static com.tencent.trtc.TRTCCloudDef.TRTCRoleAnchor;
import static com.tencent.trtc.TRTCCloudDef.TRTC_QUALITY_Bad;
import static com.tencent.trtc.TRTCCloudDef.TRTC_QUALITY_Down;
import static com.tencent.trtc.TRTCCloudDef.TRTC_QUALITY_Excellent;
import static com.tencent.trtc.TRTCCloudDef.TRTC_QUALITY_Good;
import static com.tencent.trtc.TRTCCloudDef.TRTC_QUALITY_Poor;
import static com.tencent.trtc.TRTCCloudDef.TRTC_QUALITY_UNKNOWN;
import static com.tencent.trtc.TRTCCloudDef.TRTC_QUALITY_Vbad;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.tencent.rtmp.ui.TXCloudVideoView;
import com.tencent.trtc.TRTCCloud;
import com.tencent.trtc.TRTCCloudDef;
import com.tencent.trtc.TRTCCloudListener;
import java.util.ArrayList;
//音视频直播间 观众
public class AudioVideoAudienceActivity extends AppCompatActivity {
private TRTCCloud mTRTCCloud;
private TXCloudVideoView mTxCloudVideoView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
mTxCloudVideoView = findViewById(R.id.audience_tx_vv);
// 设置订阅模式 TODO??
mTRTCCloud.setDefaultStreamRecvMode(true, true);
//设置监听
initListener();
//进入房间
initEnterRoom();
//订阅音视频流
initSubscriptionAudioVideo();
}
//订阅音视频流
private void initSubscriptionAudioVideo() {
// Mute user with id denny
// mTRTCCloud.muteRemoteAudio("denny", true);
// 解除静音
mTRTCCloud.muteRemoteAudio("123", false);
// 播放 denny 的摄像头画面(我们称之为“主路画面”)
mTRTCCloud.startRemoteView("123", TRTCCloudDef.TRTC_VIDEO_STREAM_TYPE_BIG, mTxCloudVideoView);
// 将 denny 的主路画面切换到一个悬浮的小窗口中(假如该迷你小窗口为 miniFloatingView)
// mTRTCCloud.updateRemoteView("denny", TRTCCloudDef.TRTC_VIDEO_STREAM_TYPE_BIG,miniFloatingView);
// 将远端用户 denny 的主路画面设置为填充模式,并开启左右镜像模式
TRTCCloudDef.TRTCRenderParams param = new TRTCCloudDef.TRTCRenderParams();
//填充模式
param.fillMode = TRTCCloudDef.TRTC_VIDEO_RENDER_MODE_FILL;
//左右镜像
param.mirrorType = TRTCCloudDef.TRTC_VIDEO_MIRROR_TYPE_DISABLE;
//TODO ?
mTRTCCloud.setRemoteRenderParams("123", TRTCCloudDef.TRTC_VIDEO_STREAM_TYPE_BIG, param);
}
// 进入房间
private void initEnterRoom() {
// 设置美颜等级
mTRTCCloud.getBeautyManager().setBeautyLevel(100);
TRTCCloudDef.TRTCParams params = new TRTCCloudDef.TRTCParams();
//设置sdkAppId
//userID roomId
params.sdkAppId = 123;
//用户的id
params.userId = "123";
//直播间号
params.roomId = 123;
//直播间号
params.strRoomId = "";
//用户进入房间的鉴权
params.userSig = "eJyrVareCeYrSy1SslI";
//指定角色为观众
params.role = TRTCCloudDef.TRTCRoleAudience;
//进入房间
//在线直播的场景 TRTCCloudDef.TRTC_APP_SCENE_LIVE
mTRTCCloud.enterRoom(params, TRTCCloudDef.TRTC_APP_SCENE_LIVE);
}
//初始化监听
private void initListener() {
// 创建 SDK 实例(单例模式)并设置事件监听器
// Create trtc instance(singleton) and set up event listeners
mTRTCCloud = TRTCCloud.sharedInstance(getApplicationContext());
mTRTCCloud.setListener(new TRTCCloudListener() {
//错误的信息
@Override
public void onError(int errCode, String errMsg, Bundle extraInfo) {
super.onError(errCode, errMsg, extraInfo);
Toast.makeText(getApplicationContext(), "由于" + errMsg + "退出直播间", Toast.LENGTH_SHORT).show();
// 退出房间 TODO 如果有错误码 就判断
mTRTCCloud.exitRoom();
}
//进入房间 如果是复数就失败
@Override
public void onEnterRoom(long result) {
if (result > 0) {
Log.d("TAG", "Enter room succeed");
} else {
Log.d("TAG", "Enter room failed");
}
}
//退出房间
@Override
public void onExitRoom(int reason) {
super.onExitRoom(reason);
}
//链接断了
@Override
public void onConnectionLost() {
super.onConnectionLost();
}
//切换主播失败
@Override
public void onSwitchRoom(int errCode, String errMsg) {
if (errCode != 0) {
Log.d("TAG", "Switching operation failed...");
}
}
// 感知远端用户视频状态的变化,并更新开启了摄像头的用户列表(mCameraUserList)
@Override
public void onUserVideoAvailable(String userId, boolean available) {
// available?mCameraUserList.add(userId) : mCameraUserList.remove(userId);
}
// 感知远端用户音频状态的变化,并更新开启了麦克风的用户列表(mMicrophoneUserList)
@Override
public void onUserAudioAvailable(String userId, boolean available) {
// available?mMicrophoneUserList.add(userId) : mMicrophoneUserList.remove(userId);
}
// 感知远端用户进入房间的通知,并更新远端用户列表(mUserList)
@Override
public void onRemoteUserEnterRoom(String userId) {
// mUserList.add(userId);
}
// 感知远端用户离开房间的通知,并更新远端用户列表(mUserList)
@Override
public void onRemoteUserLeaveRoom(String userId, int reason) {
// mUserList.remove(userId);
}
//判断网络状态
@Override
public void onNetworkQuality(TRTCCloudDef.TRTCQuality localQuality, ArrayList remoteQuality) {
super.onNetworkQuality(localQuality, remoteQuality);
// Get your local network quality
switch (localQuality.quality) {
case TRTC_QUALITY_UNKNOWN:
Log.d("TAG", "SDK has not yet sensed the current network quality.");
break;
case TRTC_QUALITY_Excellent:
Log.d("TAG", "The current network is very good.");
break;
case TRTC_QUALITY_Good:
Log.d("TAG", "The current network is good.");
break;
case TRTC_QUALITY_Poor:
Log.d("TAG", "The current network quality barely meets the demand.");
break;
case TRTC_QUALITY_Bad:
Log.d("TAG", "The current network is poor, and there may be significant freezes and call delays.");
break;
case TRTC_QUALITY_Vbad:
Log.d("TAG", "The current network is very poor, the communication quality cannot be guaranteed");
break;
case TRTC_QUALITY_Down:
Log.d("TAG", "The current network does not meet the minimum requirements.");
break;
default:
break;
}
// Get the network quality of remote users
for (TRTCCloudDef.TRTCQuality info : remoteQuality) {
Log.d("TAG", "remote user : = " + info.userId + ", quality = " + info.quality);
}
}
});
}
}
6.直播主播推流及所有相关操作API
代码如下(示例):
package com.wlsj2022.myapplication;
import static com.tencent.liteav.audio.TXAudioEffectManager.TXVoiceChangerType.TXLiveVoiceChangerType_7;
import static com.tencent.liteav.audio.TXAudioEffectManager.TXVoiceReverbType.TXLiveVoiceReverbType_3;
import static com.tencent.live2.V2TXLiveCode.V2TXLIVE_ERROR_INVALID_LICENSE;
import static com.tencent.live2.V2TXLiveDef.V2TXLiveVideoResolution.V2TXLiveVideoResolution160x160;
import static com.tencent.live2.V2TXLiveDef.V2TXLiveVideoResolution.V2TXLiveVideoResolution1920x1080;
import static com.tencent.live2.V2TXLiveDef.V2TXLiveVideoResolution.V2TXLiveVideoResolution960x540;
import static com.tencent.live2.V2TXLiveDef.V2TXLiveVideoResolutionMode.V2TXLiveVideoResolutionModeLandscape;
import static com.tencent.live2.V2TXLiveDef.V2TXLiveVideoResolutionMode.V2TXLiveVideoResolutionModePortrait;
import static com.tencent.rtmp.TXLiveConstants.BEAUTY_STYLE_PITU;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.SurfaceView;
import android.view.TextureView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.tencent.liteav.audio.TXAudioEffectManager;
import com.tencent.liteav.beauty.TXBeautyManager;
import com.tencent.liteav.device.TXDeviceManager;
import com.tencent.live2.V2TXLiveCode;
import com.tencent.live2.V2TXLiveDef;
import com.tencent.live2.V2TXLivePlayer;
import com.tencent.live2.V2TXLivePlayerObserver;
import com.tencent.live2.V2TXLivePusher;
import com.tencent.live2.V2TXLivePusherObserver;
import com.tencent.live2.impl.V2TXLivePusherImpl;
import com.tencent.rtmp.TXLivePlayer;
import com.tencent.rtmp.ui.TXCloudVideoView;
import java.io.UnsupportedEncodingException;
//直接主播推流
public class LiveRoomAnchorActivity extends AppCompatActivity {
private V2TXLivePusher mMLivePusher;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_live_room);
// 想回放协议HLS 延迟高
// 指定对应的直播协议为 RTMP RTSP,该协议不支持连麦
// V2TXLivePusher mLivePusher = new V2TXLivePusherImpl(this, V2TXLiveDef.V2TXLiveMode.TXLiveMode_RTMP);
// 指定对应的直播协议为 RTC,该协议支持连麦。如果在直播过程中有连麦需求,需要选择该协议
mMLivePusher = new V2TXLivePusherImpl(this, V2TXLiveDef.V2TXLiveMode.TXLiveMode_RTC);
// 启动本地摄像头预览
TXCloudVideoView mPusherView = (TXCloudVideoView) findViewById(R.id.pusher_tx_cloud_view);
mMLivePusher.setRenderView(mPusherView);
mMLivePusher.startCamera(true);
mMLivePusher.startMicrophone();
// 开始推流startPush
// 根据推流协议传入对应的 URL 即可启动推流, RTMP 协议以 rtmp:// 开头,该协议不支持连麦
//String url = "rtmp://test.com/live/streamid?txSecret=xxxxx&txTime=xxxxxxxx";
// 根据推流协议传入对应的 URL 即可启动推流, RTC 协议以 trtc:// 开头,该协议支持连麦
//TODO 申请
String url = "trtc://cloud.tencent.com/push/streamid?sdkappid=1400188888&userId=A&usersig=xxxxx";
//不开摄像头的时候 只推音频
mMLivePusher.startMicrophone();
//录屏的推流
mMLivePusher.startScreenCapture();
int ret = mMLivePusher.startPush(url);
if (ret == V2TXLIVE_ERROR_INVALID_LICENSE) {
Log.i("TAG", "startRTMPPush: license 校验失败");
}
// 结束推流
// mLivePusher.stopPush();
// 设定画面清晰度
V2TXLiveDef.V2TXLiveVideoEncoderParam videoEncoderParam = new V2TXLiveDef.V2TXLiveVideoEncoderParam(V2TXLiveVideoResolution1920x1080);
//设置竖屏模式下的分辨率
//V2TXLiveVideoResolutionModeLandscape
videoEncoderParam.videoResolutionMode =
V2TXLiveVideoResolutionModePortrait;
// 判断横竖屏并设置正确的分辨率
// videoEncoderParam.videoResolutionMode = isLandscape ? V2TXLiveVideoResolutionModeLandscape : V2TXLiveVideoResolutionModePortrait;
//设置画面的清晰
mMLivePusher.setVideoQuality(videoEncoderParam);
//设置美颜
TXBeautyManager beautyManager = mMLivePusher.getBeautyManager();
//设置美颜的模式 介于光滑和自然之间
beautyManager.setBeautyStyle(BEAUTY_STYLE_PITU);
//美颜的级别
beautyManager.setBeautyLevel(1);
//美白的级别
beautyManager.setWhitenessLevel(1);
//设置红润的级别
beautyManager.setRuddyLevel(1);
// 选择期望的色彩滤镜文件,滤镜文件可以在小直播 App 的资源文件中获取(以 tuibeauty_filter_ 开头的 .png 文件)。
// Bitmap filterBmp = decodeResource(getResources(), R.drawable.tuibeauty_filter_biaozhun);
//设置滤镜
// mMLivePusher.getBeautyManager().setFilter(filterBmp);
//设置滤镜的浓度
// mMLivePusher.getBeautyManager().setFilterStrength(0.5f);
// TXDeviceManager.TXAudioRoute.TXAudioRouteEarpiece=
//设置镜像
mMLivePusher.setEncoderMirror(true);
TXAudioEffectManager audioEffectManager = mMLivePusher.getAudioEffectManager();
//开启耳返
audioEffectManager.enableVoiceEarMonitor(true);
//设置混响效果
audioEffectManager.setVoiceReverbType(TXLiveVoiceReverbType_3);
//设置变声
audioEffectManager.setVoiceChangerType(TXLiveVoiceChangerType_7);
//设置水印
mMLivePusher.setWatermark(BitmapFactory.decodeResource(getResources(),R.drawable.ic_launcher_foreground), 0.03f, 0.015f, 1f);
//主播的弱网环境提示 及一些其他提示
mMLivePusher.setObserver(new V2TXLivePusherObserver() {
@Override
public void onWarning(int code, String msg, Bundle extraInfo) {
if (code == V2TXLiveCode.V2TXLIVE_WARNING_NETWORK_BUSY) {
Toast.makeText(getApplicationContext(), "网络繁忙", Toast.LENGTH_SHORT).show();
}else if (code == V2TXLiveCode.V2TXLIVE_ERROR_REFUSED){
Toast.makeText(getApplicationContext(), "API 调用被拒绝", Toast.LENGTH_SHORT).show();
}else if(code == V2TXLiveCode.V2TXLIVE_WARNING_CAMERA_NO_PERMISSION){
Toast.makeText(getApplicationContext(), "请不要拒绝摄像头权限,否则无法开启摄像头直播", Toast.LENGTH_SHORT).show();
}
}
});
//发送SEI消息
// 答题直播:推流端将题目下发到观众端,可以做到“音-画-题”完美同步。
// 秀场直播:推流端将歌词下发到观众端,可以在播放端实时绘制出歌词特效,因而不受视频编码的降质影响。
// 在线教育:推流端将激光笔和涂鸦操作下发到观众端,可以在播放端实时地划圈划线。
int payloadType = 5;
String msg = "test";
try {
mMLivePusher.sendSeiMessage(payloadType, msg.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
//接收SEI消息 TXLivePlayer没有接收的方法 注意对象 V2TXLivePlayer
V2TXLivePlayer txLivePlayer = new V2TXLivePlayer() {
@Override
public void setObserver(V2TXLivePlayerObserver v2TXLivePlayerObserver) {
}
@Override
public int setRenderView(TXCloudVideoView txCloudVideoView) {
return 0;
}
@Override
public int setRenderView(TextureView textureView) {
return 0;
}
@Override
public int setRenderView(SurfaceView surfaceView) {
return 0;
}
@Override
public int setRenderRotation(V2TXLiveDef.V2TXLiveRotation v2TXLiveRotation) {
return 0;
}
@Override
public int setRenderFillMode(V2TXLiveDef.V2TXLiveFillMode v2TXLiveFillMode) {
return 0;
}
@Override
public int startPlay(String s) {
return 0;
}
@Override
public int stopPlay() {
return 0;
}
@Override
public int isPlaying() {
return 0;
}
@Override
public int pauseAudio() {
return 0;
}
@Override
public int resumeAudio() {
return 0;
}
@Override
public int pauseVideo() {
return 0;
}
@Override
public int resumeVideo() {
return 0;
}
@Override
public int setPlayoutVolume(int i) {
return 0;
}
@Override
public int setCacheParams(float v, float v1) {
return 0;
}
@Override
public int switchStream(String s) {
return 0;
}
@Override
public int enableVolumeEvaluation(int i) {
return 0;
}
@Override
public int snapshot() {
return 0;
}
@Override
public int enableObserveVideoFrame(boolean b, V2TXLiveDef.V2TXLivePixelFormat v2TXLivePixelFormat, V2TXLiveDef.V2TXLiveBufferType v2TXLiveBufferType) {
return 0;
}
@Override
public int enableReceiveSeiMessage(boolean b, int i) {
return 0;
}
@Override
public void showDebugView(boolean b) {
}
@Override
public int setProperty(String s, Object o) {
return 0;
}
};
// 根据payloadType得到信息
txLivePlayer.enableReceiveSeiMessage(true, payloadType);
}
}
该处使用的url网络请求的数据。
7.直播观众拉流及连麦互动等操作API代码如下(示例):
package com.wlsj2022.myapplication;
import static com.tencent.live2.V2TXLiveDef.V2TXLiveFillMode.V2TXLiveFillModeFit;
import static com.tencent.live2.V2TXLiveDef.V2TXLiveRotation.V2TXLiveRotation0;
import android.graphics.Bitmap;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import com.tencent.live2.V2TXLiveDef;
import com.tencent.live2.V2TXLivePlayer;
import com.tencent.live2.V2TXLivePlayerObserver;
import com.tencent.live2.V2TXLivePusher;
import com.tencent.live2.impl.V2TXLivePlayerImpl;
import com.tencent.live2.impl.V2TXLivePusherImpl;
import com.tencent.rtmp.ui.TXCloudVideoView;
import java.util.ArrayList;
//直播观众拉流
public class LiveRoomAudienceActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_live_room_audience);
//mPlayerView 即 step3 中添加的界面 view
TXCloudVideoView mView = (TXCloudVideoView) findViewById(R.id.video_view);
//创建 player 对象
V2TXLivePlayer mLivePlayer = new V2TXLivePlayerImpl(this);
//关联 player 对象与界面 view
mLivePlayer.setRenderView(mView);
//直播URL
String flvUrl = "http://2157.liveplay.myqcloud.com/live/2157_xxxx.flv";
//想使用快直播 直接填快直播的URL即可
String flvQuicklyUrl = "webrtc://{Domain}/{AppName}/{StreamName}";
//开始播放
mLivePlayer.startPlay(flvUrl);
// 设置填充模式 将图像等比例缩放,适配最长边,缩放后的宽和高都不会超过显示区域,居中显示,画面可能会留有黑边
mLivePlayer.setRenderFillMode(V2TXLiveFillModeFit);
// 设置画面渲染方向 V2TXLiveRotation90 顺时针旋转90度
mLivePlayer.setRenderRotation(V2TXLiveRotation0);
// 暂停 TODO:按钮
mLivePlayer.pauseAudio();
mLivePlayer.pauseVideo();
// 继续
mLivePlayer.resumeAudio();
mLivePlayer.resumeVideo();
//播放结束
mLivePlayer.stopPlay();
//截取一帧 用户行为或者缓存用
mLivePlayer.setObserver(new MyPlayerObserver());
mLivePlayer.snapshot();
//自动模式 自动模式网络自适应 观众端的网络越好,延迟就越低;观众端网络越差,延迟就越高
mLivePlayer.setCacheParams(1.0f, 5.0f);
// 单独功能 发起连麦
// 1 主播 RTC 推流 主播 A 开始推流,调用 V2TXLivePusher 组件开始主播 A 的推流。
V2TXLivePusher pusher = new V2TXLivePusherImpl(this, V2TXLiveDef.V2TXLiveMode.TXLiveMode_RTC);
String pushURLA= "trtc://cloud.tencent.com/push/streamid?sdkappid=1400188888&userId=A&usersig=xxx";
pusher.startPush(pushURLA);
// 2 观众拉流 所有观众观看主播 A 直播,调用 V2TXLivePlayer 开始播放主播 A 的流。URL 拼装方案请参见 如何拼装 URL。
V2TXLivePlayer player = new V2TXLivePlayerImpl(this);
String playURLA= "webrtc://3891.liveplay.myqcloud.com/live/streamidA";
player.startPlay(playURLA);
//3观众发起连麦startPush 其中观众 B 调用 V2TXLivePusher 发起推流(后续会称呼为连麦观众 B)。
String pushURLB= "trtc://cloud.tencent.com/push/streamid?sdkappid=1400188888&userId=B&usersig=xxx";
//发起连麦startPush
pusher.startPush(pushURLB);
// 4. 进入连麦状态 主播 A 调用 V2TXLivePlayer 使用 RTC 协议拉取放连麦观众 B 的流。
String playURLB= "trtc://cloud.tencent.com/play/streamid?sdkappid=1400188888&userId=B&usersig=xxx&appscene=live";
player.startPlay(playURLB);
//同时,连麦观众 B 调用 V2TXLivePlayer 切换至 RTC 协议,开始播放主播 A 的流。
playURLA= "trtc://cloud.tencent.com/play/streamid?sdkappid=1400188888&userId=A&usersig=xxx&appscene=live";
player.startPlay(playURLA);
// 5.混流
V2TXLiveDef.V2TXLiveTranscodingConfig config = new V2TXLiveDef.V2TXLiveTranscodingConfig();
// 设置分辨率为 720 × 1280, 码率为 1500kbps,帧率为 20FPS
config.videoWidth = 720;
config.videoHeight = 1280;
config.videoBitrate = 1500;
config.videoFramerate = 20;
config.videoGOP = 2;
config.audioSampleRate = 48000;
config.audioBitrate = 64;
config.audioChannels = 2;
config.mixStreams = new ArrayList<>();
// 主播摄像头的画面位置
V2TXLiveDef.V2TXLiveMixStream local = new V2TXLiveDef.V2TXLiveMixStream();
local.userId = "localUserId";
local.streamId = null; // 本地画面不用填写 streamID,远程需要
local.x = 0;
local.y = 0;
local.width = 400;
local.height = 500;
local.zOrder = 0; // zOrder 为 0 代表主播画面位于最底层
config.mixStreams.add(local);
// 连麦者的画面位置
V2TXLiveDef.V2TXLiveMixStream remoteA = new V2TXLiveDef.V2TXLiveMixStream();
remoteA.userId = "remoteUserIdA";
remoteA.streamId = "remoteStreamIdA"; // 本地画面不用填写 streamID,远程需要
remoteA.x = 400; //仅供参考
remoteA.y = 800; //仅供参考
remoteA.width = 180; //仅供参考
remoteA.height = 240; //仅供参考
remoteA.zOrder = 1;
config.mixStreams.add(remoteA);
// 连麦者的画面位置
V2TXLiveDef.V2TXLiveMixStream remoteB = new V2TXLiveDef.V2TXLiveMixStream();
remoteB.userId = "remoteUserIdB";
remoteB.streamId = "remoteStreamIdB"; // 本地画面不用填写 streamID,远程需要
remoteB.x = 400; //仅供参考
remoteB.y = 800; //仅供参考
remoteB.width = 180; //仅供参考
remoteB.height = 240; //仅供参考
remoteB.zOrder = 1;
config.mixStreams.add(remoteB);
// 发起云端混流
pusher.setMixTranscodingConfig(config);
}
// 在MyPlayerObserver的回调接口
private class MyPlayerObserver extends V2TXLivePlayerObserver {
// onSnapshotComplete中获取屏幕截图
@Override
public void onSnapshotComplete(V2TXLivePlayer v2TXLivePlayer, Bitmap bitmap) {
}
//定时触发的状态通知
@Override
public void onStatisticsUpdate(V2TXLivePlayer player, V2TXLiveDef.V2TXLivePlayerStatistics statistics) {
super.onStatisticsUpdate(player, statistics);
// 当前 App 的 CPU 使用率(%)
int appCpu = statistics.appCpu;
// 帧率(fps)
int fps = statistics.fps;
}
}
}
总结
提示:这里对文章进行总结:
就是这样



