WGShare.Client.Electron/src/utils/package/agora.ts

342 lines
12 KiB
TypeScript

import { message } from "antd";
import {
createAgoraRtcEngine,
ClientRoleType,
VideoSourceType,
VideoViewSetupMode,
ScreenCaptureSourceType,
RenderModeType,
ChannelProfileType,
MediaRecorderContainerFormat,
MediaRecorderStreamType
} from "agora-electron-sdk";
import { GetRoomRtcToken } from "@/api/Home/Index";
import { storage } from '@/utils';
const option: any = {
appId: 'dcfc466a6ecb4a1f972630065dfb1e75',
token: '',
channelId: '',
uid: ''
}
let iMediaRecorder: any = '';
let rtcEngine: any = '';
const agora = {
// 初始化
init: async (bool: boolean = false) => {
rtcEngine = createAgoraRtcEngine();
await rtcEngine.initialize({
appId: option.appId,
});
if (bool) {
const setting = JSON.parse(storage.getItem('setting') as string)
if (setting.videoDeviceId) {
agora.setVideoDeviceManager(setting.videoDeviceId) //通过设备 ID 指定视频采集设备。
} else {
agora.setVideoDeviceManager(rtcEngine.getVideoDeviceManager().getDevice())
}
if (setting.playBackDeviceId) agora.setPlaybackDevice(setting.playBackDeviceId) //指定播放设备
if (setting.playBackVolume) agora.setPlaybackDeviceVolume(setting.playBackVolume) // 设置播放设备音量
if (setting.ecordingDeviceId) agora.setRecordingDevice(setting.ecordingDeviceId) // 设置音频采集设备
if (setting.ecordingVolume) agora.setRecordingDeviceVolume(setting.ecordingVolume) // 设置音频设备音量
}
},
// 事件回调
registerEventHandler: ({ onJoinChannelSuccess, onUserJoined, onUserOffline, onAudioVolumeIndication }: any) => {
rtcEngine.registerEventHandler({
// 监听本地用户加入频道事件
onJoinChannelSuccess: async (info: any, elapsed: any) => {
await onJoinChannelSuccess(info, elapsed)
},
// 监听远端用户加入频道事件
onUserJoined: async (info: any, remoteUid: any, elapsed: any) => {
await onUserJoined(info, remoteUid, elapsed)
},
// 监听用户离开频道事件
onUserOffline: async (info: any, remoteUid: any, reason: any) => {
await onUserOffline(info, remoteUid, reason)
},
// // 视频发布状态改变回调
// onVideoPublishStateChanged: (source: any, channel: any, oldState: any, newState: any, elapseSinceLastState: any) => {
// if (newState === 1) {
// }
// },
// // 音频发布状态改变回调
// onAudioPublishStateChanged: (channel: any, oldState: any, newState: any, elapseSinceLastState: any) => {
// if (newState === 1) {
// }
// },
// // 用户音量提示回调。
onAudioVolumeIndication: async (connection: any, speakers: any, speakerNumber: any, totalVolume: any,) => {
const percentage = (totalVolume / 255) * 100
await onAudioVolumeIndication(percentage)
}
});
},
// 本地加入
setupLocalVideo: async (item: any) => {
await rtcEngine.setupLocalVideo({
renderMode: RenderModeType.RenderModeFit,
sourceType: item.sourceType,
uid: item.uid,
view: item.view,
setupMode: VideoViewSetupMode.VideoViewSetupAdd,
});
},
// 远端加入
setupRemoteVideoJoin: async (item: any) => {
await rtcEngine.setupRemoteVideo(
{
renderMode: RenderModeType.RenderModeFit,
sourceType: VideoSourceType.VideoSourceRemote,
uid: item.uid,
view: item.view,
setupMode: VideoViewSetupMode.VideoViewSetupAdd,
},
{ channelId: item.channelId },
);
},
// 退出
setupRemoteVideo: async (item: any) => {
await rtcEngine.setupRemoteVideo(
{
renderMode: RenderModeType.RenderModeFit,
sourceType: VideoSourceType.VideoSourceRemote,
uid: item.uid,
view: item.view,
setupMode: VideoViewSetupMode.VideoViewSetupRemove,
},
);
},
// 销毁
release: () => {
rtcEngine.release()
},
// 离开频道
leaveChannel: async () => {
await rtcEngine.leaveChannel({
stopAudioMixing: true,
stopAllEffect: true,
stopMicrophoneRecording: true,
})
agora.stopScreenCapture()
agora.release()
},
// 加入频道
joinChannel: () => {
rtcEngine.joinChannel(option.token, option.channelId, option.uid, {
autoSubscribeAudio: true,
autoSubscribeVideo: true,
publishMicrophoneTrack: true,
publishCameraTrack: true,
clientRoleType: ClientRoleType.ClientRoleBroadcaster,
publishScreenTrack: false,
});
},
// 停止共享屏幕
stopScreenCapture: () => {
rtcEngine.stopScreenCapture();
},
// 取消或恢复发布本地音频流
muteLocalAudioStream: (mute: any) => {
rtcEngine.muteLocalAudioStream(mute)
},
// 取消或恢复发布本地视频流
muteLocalVideoStream: (mute: any) => {
rtcEngine.muteLocalVideoStream(mute)
},
// 摄像头采集
setCameraCapture: () => {
agora.stopScreenCapture()
// rtcEngine.destroyRendererByConfig(option.sourceType, option.channelId, option.account)
agora.setupLocalVideo({
account: Number(option.uid),
view: document.getElementById(`video-${option.uid}`),
channelId: option.channelId,
sourceType: VideoSourceType.VideoSourceCameraPrimary,
})
rtcEngine.startCameraCapture(VideoSourceType.VideoSourceCamera, {})
},
// 加入频道
setJoinChannel: async (data: any) => {
option.token = data.token;
option.channelId = data.channelId;
option.uid = Number(data.uid);
agora.joinChannel()
},
// 桌面捕获音频和视频的媒体源的信息
getDesktopCapturerVideo: async () => {
return rtcEngine.getScreenCaptureSources({ width: 300, height: 300 }, { width: 300, height: 300 }, true);
},
// 共享屏幕采集
setDesktopCapturerVideo: async (targetSource: any) => {
// await rtcEngine.stopCameraCapture(option.sourceType)
// rtcEngine.destroyRendererByConfig(option.sourceType, option.channelId, option.account)
const user = JSON.parse(storage.getItem('user') as string)
rtcEngine.joinChannelEx(
option.token,
{ channelId: option.channelId, localUid: Number(user.uid) },
{
autoSubscribeAudio: false,
autoSubscribeVideo: false,
publishMicrophoneTrack: false,
publishCameraTrack: false,
clientRoleType: ClientRoleType.ClientRoleBroadcaster,
publishScreenTrack: true,
}
);
await agora.setupLocalVideo({
account: Number(user.uid),
view: document.getElementById(`look-video`),
channelId: option.channelId,
sourceType: VideoSourceType.VideoSourceScreen,
})
agora.stopScreenCapture();
if (
targetSource.type ===
ScreenCaptureSourceType.ScreencapturesourcetypeScreen
) {
rtcEngine.startScreenCaptureByDisplayId(
targetSource.sourceId,
{},
{
windowFocus: true,
enableHighLight: true,
highLightColor: 0xFF99CC00,
}
);
} else {
rtcEngine.startScreenCaptureByWindowId(
targetSource.sourceId,
{},
{
windowFocus: true,
enableHighLight: true,
highLightColor: 0xFF99CC00,
}
);
}
},
// 停止录制音视频
stopRecording: () => {
iMediaRecorder.stopRecording()
rtcEngine.destroyMediaRecorder(iMediaRecorder)
iMediaRecorder = ""
},
// 开始录制音视频
startRecording: (uid: number) => {
iMediaRecorder = rtcEngine.createMediaRecorder({
channelId: option.channelId,
uid,
})
iMediaRecorder.setMediaRecorderObserver({
// 录制状态发生改变回调。
onRecorderStateChanged: (channelId: any, uid: any, state: any, reason: any) => {
switch (reason) {
case 1:
message.error('录制文件写入失败')
break;
case 2:
message.error('没有可录制的音视频流或者录制的音视频流中断超过 5 秒')
break;
case 3:
message.error('录制时长超出上限')
break;
}
},
// 录制信息更新回调。
onRecorderInfoUpdated: (channelId: any, uid: any, info: any) => {
message.success(`文件已保存至${info.fileName}`)
},
})
const setting = JSON.parse(storage.getItem('setting') as string)
iMediaRecorder.startRecording({
storagePath: `${setting.recordingFilesPath}${+new Date()}.mp4`, //录音文件在本地保存的绝对路径,需精确到文件名及格式
containerFormat: MediaRecorderContainerFormat.FormatMp4, //录制文件的格式
streamType: MediaRecorderStreamType.StreamTypeBoth, //录制内容
maxDurationMs: 7200000, //maxDurationMs
})
},
// 获取系统中所有的视频设备列表。
getVideoDeviceManager: async (): Promise<any> => {
return {
list: rtcEngine.getVideoDeviceManager().enumerateVideoDevices(),
item: rtcEngine.getVideoDeviceManager().getDevice()
}
},
// 通过设备 ID 指定视频采集设备。
setVideoDeviceManager: async (deviceIdUTF8: string) => {
await rtcEngine.getVideoDeviceManager().setDevice(deviceIdUTF8)
},
// 开启本地视频预览
startPreview: async (id: string, uid: number): Promise<void> => {
rtcEngine.enableVideo();
rtcEngine.startPreview();
await GetRoomRtcToken(`${+new Date()}`).then(async (res) => {
await rtcEngine.joinChannelEx(res.data, {
channelId: `${+new Date()}`,
localUid: uid,
}, {
channelProfile: ChannelProfileType.ChannelProfileLiveBroadcasting,
clientRoleType: ClientRoleType.ClientRoleBroadcaster,
publishMicrophoneTrack: true,
publishCameraTrack: true,
autoSubscribeAudio: true,
autoSubscribeVideo: true,
});
rtcEngine.setupLocalVideo({
sourceType: VideoSourceType.VideoSourceCameraPrimary,
uid,
view: document.getElementById(id),
setupMode: VideoViewSetupMode.VideoViewSetupAdd,
});
})
},
// 获取输入输出设备列表
getAudioMediaList: async () => {
return {
playBackList: rtcEngine.getAudioDeviceManager().enumeratePlaybackDevices(),
ecordingList: rtcEngine.getAudioDeviceManager().enumerateRecordingDevices(),
playBackItem: rtcEngine.getAudioDeviceManager().getPlaybackDefaultDevice(),
ecordingItem: rtcEngine.getAudioDeviceManager().getRecordingDefaultDevice(),
ecordingVolume: rtcEngine.getAudioDeviceManager().getRecordingDeviceVolume(),
}
},
// 启动音频播放设备测试。
startPlaybackDeviceTest: async () => {
await rtcEngine.getAudioDeviceManager().startPlaybackDeviceTest('https://wgshare.oss-cn-chengdu.aliyuncs.com/TestAudio.mp3')
},
// 停止音频播放设备测试。
stopPlaybackDeviceTest: async () => {
await rtcEngine.getAudioDeviceManager().stopPlaybackDeviceTest()
},
// 设置播放设备音量
setPlaybackDeviceVolume: async (volume: number) => {
await rtcEngine.getAudioDeviceManager().setPlaybackDeviceVolume(volume)
},
// 指定播放设备
setPlaybackDevice: async (deviceId: string) => {
await rtcEngine.getAudioDeviceManager().setPlaybackDevice(deviceId)
},
// 启动音频采集设备测试
startRecordingDeviceTest: async (indicationInterval: number) => {
await rtcEngine.getAudioDeviceManager().startRecordingDeviceTest(indicationInterval)
},
// 设置音频设备音量
setRecordingDeviceVolume: async (volume: number) => {
await rtcEngine.getAudioDeviceManager().setRecordingDeviceVolume(volume)
},
// 设置音频采集设备
setRecordingDevice: async (deviceId: string) => {
await rtcEngine.getAudioDeviceManager().setRecordingDevice(deviceId)
},
// 停止音频采集设备测试
stopRecordingDeviceTest: async () => {
await rtcEngine.getAudioDeviceManager().stopRecordingDeviceTest()
},
}
export default agora;