简介
如果用户正在进行摄像头或者麦克风的采集推流,推流过程中正在使用的摄像头或者麦克风设备被拔出。此时推流不会停止,但是由于视频流或者音频流采集中断,会导致播放端出现音画不同步等问题。
可通过以下代码实现推流过程中自动切换到剩余可用设备,恢复采集保证推流继续顺利进行。
代码示例
1、初始化
SDK 初始化代码请参考 入门指南 ,这里假设我们已经完成了初始化,获取了 SDK 实例 livePusher 。
2、获取设备管理对象
设备管理对象用于获取设备列表、切换设备。
const deviceManager = livePusher.getDeviceManager();
3、监听事件
通过 setObserver() 接口中的回调事件 onWarning 监听流异常中断事件,然后进行切换设备的操作。
livePusher.setObserver({
onWarning: function (code, message, data) {
const WARNING_CODE = {
CAMERA_INTERRUPTED: -1005, // 摄像头中断事件
MICROPHONE_INTERRUPTED: -1006 // 麦克风中断事件
};
if (code === WARNING_CODE.CAMERA_INTERRUPTED) {
// 摄像头中断,查找剩余可用摄像头
deviceManager.getDevicesList('video').then(function (devices) {
if (devices.length > 0 && devices[0].deviceId) {
// 切换摄像头设备
deviceManager.switchCamera(devices[0].deviceId, data.streamId);
console.log('摄像头采集异常中断,自动切换');
} else {
// 结束推流
if (livePusher.isPushing()) {
livePusher.stopPush();
console.log('摄像头采集异常中断,推流结束');
}
// 停止采集
livePusher.stopCamera();
console.log('停止采集摄像头');
}
});
} else if (code === WARNING_CODE.MICROPHONE_INTERRUPTED) {
// 麦克风中断,查找剩余可用麦克风
deviceManager.getDevicesList('audio').then(function (devices) {
if (devices.length > 0 && devices[0].deviceId) {
// 切换麦克风设备
deviceManager.switchMicrophone(devices[0].deviceId, data.streamId);
console.log('麦克风采集异常中断,自动切换');
} else {
// 结束推流
if (livePusher.isPushing()) {
livePusher.stopPush();
console.log('麦克风采集异常中断,推流结束');
}
// 停止采集
livePusher.stopMicrophone();
console.log('停止采集麦克风');
}
});
}
}
});
说明:
如果通过 getDevicesList() 接口获取剩余设备不存在时,可以考虑给用户提示,然后结束推流。