feige
2025-05-21 2b08f5948818994816b08dbe9ea9532286787e78
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
/*
 * @Description: 屏幕分享
 * @Date: 2022-03-16 10:34:54
 * @LastEditTime: 2022-04-01 11:57:06
 */
import TRTC from 'trtc-js-sdk';
import LibGenerateTestUserSig from '@/utils/lib-generate-test-usersig.min.js';
 
export default {
  data() {
    return {
      shareClient: null,
      shareLocalStream: null,
      isShareJoined: false,
      isSharePublished: false,
    };
  },
 
  computed: {
    shareUserId() {
      return `share_${this.userId}`;
    },
    shareUserSig() {
      if (this.sdkAppId && this.secretKey && this.shareUserId) {
        const generator = new LibGenerateTestUserSig(this.sdkAppId, this.secretKey, 604800);
        return generator.genTestUserSig(this.shareUserId);
      }
      return '';
    },
  },
 
  methods: {
    // 初始化屏幕分享 client
    initShareClient() {
      this.shareClient = TRTC.createClient({
        mode: 'rtc',
        sdkAppId: this.sdkAppId,
        userId: this.shareUserId,
        userSig: this.shareUserSig,
        autoSubscribe: false,
      });
      this.addSuccessLog(`Client [${this.shareUserId}] created.`);
      this.handleShareClientEvents();
    },
 
    // 初始化屏幕分享 stream
    async initShareLocalStream() {
      this.shareLocalStream = TRTC.createStream({
        screenAudio: false,
        screen: true,
        userId: this.shareUserId,
      });
      this.shareLocalStream.setScreenProfile('1080p');
      try {
        await this.shareLocalStream.initialize();
        this.addSuccessLog(`ShareStream [${this.shareUserId}] initialized.`);
      } catch (error) {
        this.addFailedLog(`ShareStream failed to initialize. Error: ${error.message}}.`);
        switch (error.name) {
          case 'NotReadableError':
            alert('屏幕分享失败,请确保系统允许当前浏览器获取屏幕内容');
            throw error;
          case 'NotAllowedError':
            if (error.message.includes('Permission denied by system')) {
              alert('屏幕分享失败,请确保系统允许当前浏览器获取屏幕内容');
            } else {
              console.log('User refused to share the screen');
            }
            throw error;
          default:
            return;
        }
      }
      this.handleShareStreamEvents();
    },
 
    // 销毁本地屏幕分享流
    destroyShareLocalStream() {
      this.shareLocalStream.stop();
      this.shareLocalStream.close();
      this.shareLocalStream = null;
    },
 
    // 处理屏幕分享 client 进房
    async handleShareJoin() {
      if (this.isShareJoined) {
        console.error('ShareClient has joined');
        return;
      }
      try {
        await this.shareClient.join({ roomId: this.roomId });
        this.isShareJoined = true;
 
        this.addSuccessLog(`ShareClient [${this.shareUserId}] join success.`);
      } catch (error) {
        console.log('shareRTC handleJoin error', error);
        this.addFailedLog(`ShareClient [${this.shareUserId}] join failed. ${error.message}.`);
        this.reportFailedEvent('startScreenShare', error, 'share');
      }
    },
 
    // 屏幕分享 client 发布屏幕分享流
    async handleSharePublish() {
      if (this.isSharePublished) {
        console.error('ShareClient has published');
        return;
      }
      try {
        await this.shareClient.publish(this.shareLocalStream);
        this.isSharePublished = true;
 
        this.addSuccessLog('ShareStream is published successfully.');
        this.reportSuccessEvent('startScreenShare', 'share');
      } catch (error) {
        this.addFailedLog(`ShareStream is published failed. ${error.message}.`);
        this.reportFailedEvent('startScreenShare', error, 'share');
      }
    },
 
    async handleShareUnpublish() {
      if (!this.isSharePublished) {
        console.error('ShareStream has not published');
        return;
      }
      try {
        await this.shareClient.unpublish(this.shareLocalStream);
        this.isSharePublished = false;
 
        this.addSuccessLog('ShareStream is unpublished successfully.');
      } catch (error) {
        console.log(`ShareStream unpublish failed, ${error.message}`);
        this.addFailedLog(`ShareStream unpublish failed, ${error.message}.`);
        this.reportFailedEvent('stopScreenShare', error, 'share');
      }
    },
 
    async handleShareLeave() {
      if (!this.isShareJoined) {
        console.error('ShareStream has not joined');
        return;
      }
      this.destroyShareLocalStream();
      try {
        await this.shareClient.leave();
        this.isShareJoined = false;
 
        this.addSuccessLog('ShareClient leave successfully.');
        this.reportSuccessEvent('stopScreenShare', 'share');
      } catch (error) {
        console.log(`ShareClient leave failed, ${error.message}`);
        this.addFailedLog(`ShareClient leave failed, ${error.message}.`);
        this.reportFailedEvent('stopScreenShare', error, 'share');
      }
    },
 
    handleShareClientEvents() {
      this.shareClient.on('error', (error) => {
        console.error(error);
        alert(error);
      });
      this.shareClient.on('client-banned', (event) => {
        console.warn(`client has been banned for ${event.reason}`);
      });
    },
 
    handleShareStreamEvents() {
      this.shareLocalStream.on('player-state-changed', (event) => {
        console.log(`local stream ${event.type} player is ${event.state}`);
      });
      // 当用户通过浏览器自带的按钮停止屏幕分享时,会监听到 screen-sharing-stopped 事件
      this.shareLocalStream.on('screen-sharing-stopped', async () => {
        console.log('share stream video track ended.');
        this.addSuccessLog('ScreenShare is stopped.');
        await this.handleShareUnpublish();
        await this.handleShareLeave();
      });
    },
  },
};