forked from AgoraIO-Extensions/react-native-agora
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStreamMessage.tsx
More file actions
252 lines (231 loc) · 6.29 KB
/
Copy pathStreamMessage.tsx
File metadata and controls
252 lines (231 loc) · 6.29 KB
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
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
import React, { Component, Fragment } from 'react';
import {
Alert,
Button,
PermissionsAndroid,
Platform,
StyleSheet,
Text,
TextInput,
View,
} from 'react-native';
import RtcEngine, {
ChannelProfile,
ClientRole,
DataStreamConfig,
RtcEngineContext,
RtcLocalView,
RtcRemoteView,
VideoRenderMode,
} from 'react-native-agora';
const config = require('../../../config/agora.config.json');
interface State {
channelId: string;
isJoined: boolean;
remoteUid: number[];
message?: string;
}
export default class StreamMessage extends Component<{}, State, any> {
_engine?: RtcEngine;
constructor(props: {}) {
super(props);
this.state = {
channelId: config.channelId,
remoteUid: [],
isJoined: false,
};
}
UNSAFE_componentWillMount() {
this._initEngine();
}
componentWillUnmount() {
this._engine?.destroy();
}
_initEngine = async () => {
if (Platform.OS === 'android') {
await PermissionsAndroid.requestMultiple([
'android.permission.RECORD_AUDIO',
'android.permission.CAMERA',
]);
}
this._engine = await RtcEngine.createWithContext(
new RtcEngineContext(config.appId)
);
this._addListeners();
// enable video module and set up video encoding configs
await this._engine.enableVideo();
// make myself a broadcaster
await this._engine.setChannelProfile(ChannelProfile.LiveBroadcasting);
await this._engine.setClientRole(ClientRole.Broadcaster);
// Set audio route to speaker
await this._engine.setDefaultAudioRoutetoSpeakerphone(true);
};
_addListeners = () => {
this._engine?.addListener('Warning', (warningCode) => {
console.info('Warning', warningCode);
});
this._engine?.addListener('Error', (errorCode) => {
console.info('Error', errorCode);
});
this._engine?.addListener('JoinChannelSuccess', (channel, uid, elapsed) => {
console.info('JoinChannelSuccess', channel, uid, elapsed);
// RtcLocalView.SurfaceView must render after engine init and channel join
this.setState({ isJoined: true });
});
this._engine?.addListener('LeaveChannel', (stats) => {
console.info('LeaveChannel', stats);
// RtcLocalView.SurfaceView must render after engine init and channel join
this.setState({ isJoined: false, remoteUid: [] });
});
this._engine?.addListener('UserJoined', (uid, elapsed) => {
console.info('UserJoined', uid, elapsed);
this.setState({ remoteUid: [...this.state.remoteUid, uid] });
});
this._engine?.addListener('UserOffline', (uid, reason) => {
console.info('UserOffline', uid, reason);
this.setState({
remoteUid: this.state.remoteUid.filter((value) => value !== uid),
});
});
this._engine?.addListener('StreamMessage', (uid, streamId, data) => {
console.info('UserOffline', uid, streamId, data);
Alert.alert(`Receive from uid:${uid}`, `StreamId ${streamId}:${data}`, [
{
text: 'Ok',
onPress: () => {},
},
]);
});
this._engine?.addListener(
'StreamMessageError',
(uid, streamId, error, missed, cached) => {
console.info(
'StreamMessageError',
uid,
streamId,
error,
missed,
cached
);
}
);
};
_joinChannel = async () => {
// start joining channel
// 1. Users can only see each other after they join the
// same channel successfully using the same app id.
// 2. If app certificate is turned on at dashboard, token is needed
// when joining channel. The channel name and uid used to calculate
// the token has to match the ones used for channel join
await this._engine?.joinChannel(
config.token,
this.state.channelId,
null,
config.uid
);
};
_leaveChannel = async () => {
await this._engine?.leaveChannel();
};
render() {
const { channelId, isJoined } = this.state;
return (
<View style={styles.container}>
<View style={styles.top}>
<TextInput
style={styles.input}
onChangeText={(text) => this.setState({ channelId: text })}
placeholder={'Channel ID'}
value={channelId}
/>
<Button
onPress={isJoined ? this._leaveChannel : this._joinChannel}
title={`${isJoined ? 'Leave' : 'Join'} channel`}
/>
</View>
{isJoined && this._renderVideo()}
{isJoined && this._renderToolBar()}
</View>
);
}
_renderVideo = () => {
const { remoteUid } = this.state;
return (
<View style={styles.videoContainer}>
<RtcLocalView.SurfaceView
style={styles.local}
renderMode={VideoRenderMode.Hidden}
/>
{remoteUid.length > 0 && (
<RtcRemoteView.SurfaceView
style={styles.remote}
uid={remoteUid[remoteUid.length - 1]!}
/>
)}
</View>
);
};
_renderToolBar = () => {
const { message } = this.state;
return (
<Fragment>
<Text style={styles.toolBarTitle}>Send Message</Text>
<View style={styles.infoContainer}>
<TextInput
style={styles.input}
onChangeText={(text) => this.setState({ message: text })}
placeholder={'Input Message'}
value={message}
/>
<Button title="Send" onPress={this._onPressSend} />
</View>
</Fragment>
);
};
_onPressSend = async () => {
const { message } = this.state;
if (!message) {
return;
}
const streamId = await this._engine?.createDataStreamWithConfig(
new DataStreamConfig(true, true)
);
await this._engine?.sendStreamMessage(streamId!, message);
this.setState({ message: '' });
};
}
const styles = StyleSheet.create({
container: {
flex: 1,
paddingBottom: 40,
},
top: {
width: '100%',
},
input: {
borderColor: 'gray',
borderWidth: 1,
color: 'black',
},
videoContainer: {
width: '100%',
flexDirection: 'row',
},
local: {
width: '50%',
aspectRatio: 1,
},
remote: {
width: '50%',
aspectRatio: 1,
},
toolBarTitle: {
marginTop: 48,
fontSize: 18,
fontWeight: 'bold',
},
infoContainer: {
width: '100%',
flexDirection: 'row',
},
});