-
Notifications
You must be signed in to change notification settings - Fork 229
Expand file tree
/
Copy pathCreateDataStream.m
More file actions
220 lines (188 loc) · 9.96 KB
/
CreateDataStream.m
File metadata and controls
220 lines (188 loc) · 9.96 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
//
// JoinChannelVideo.m
// APIExample
//
// Created by zhaoyongqiang on 2023/7/11.
//
#import "CreateDataStream.h"
#import "KeyCenter.h"
#import <AgoraRtcKit/AgoraRtcKit.h>
#import "VideoView.h"
#import "APIExample_OC-swift.h"
@interface CreateDataStreamEntry ()
@property (weak, nonatomic) IBOutlet UITextField *textField;
@end
@implementation CreateDataStreamEntry
- (void)viewDidLoad {
[super viewDidLoad];
}
- (IBAction)onClickJoinButton:(id)sender {
[self.textField resignFirstResponder];
UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"CreateDataStream" bundle:nil];
BaseViewController *newViewController = [storyBoard instantiateViewControllerWithIdentifier:@"CreateDataStream"];
newViewController.configs = @{@"channelName": self.textField.text};
[self.navigationController pushViewController:newViewController animated:YES];
}
@end
@interface CreateDataStream ()<AgoraRtcEngineDelegate>
@property (weak, nonatomic) IBOutlet UIView *containerView;
@property (weak, nonatomic) IBOutlet UITextField *messageField;
@property (weak, nonatomic) IBOutlet UIButton *sendButton;
@property (nonatomic, strong)VideoView *localView;
@property (nonatomic, strong)VideoView *remoteView;
@property (nonatomic, strong)AgoraRtcEngineKit *agoraKit;
@end
@implementation CreateDataStream
- (VideoView *)localView {
if (_localView == nil) {
_localView = (VideoView *)[NSBundle loadVideoViewFormType:StreamTypeLocal audioOnly:NO];
}
return _localView;
}
- (VideoView *)remoteView {
if (_remoteView == nil) {
_remoteView = (VideoView *)[NSBundle loadVideoViewFormType:StreamTypeRemote audioOnly:NO];
}
return _remoteView;
}
- (void)viewDidLoad {
[super viewDidLoad];
// layout render view
[self.localView setPlaceholder:@"Local Host".localized];
[self.remoteView setPlaceholder:@"Remote Host".localized];
[self.containerView layoutStream:@[self.localView, self.remoteView]];
// set up agora instance when view loaded
AgoraRtcEngineConfig *config = [[AgoraRtcEngineConfig alloc] init];
config.appId = KeyCenter.AppId;
config.channelProfile = AgoraChannelProfileLiveBroadcasting;
self.agoraKit = [AgoraRtcEngineKit sharedEngineWithConfig:config delegate:self];
NSString *channelName = [self.configs objectForKey:@"channelName"];
// make myself a broadcaster
[self.agoraKit setClientRole:(AgoraClientRoleBroadcaster)];
// enable video module and set up video encoding configs
[self.agoraKit enableAudio];
[self.agoraKit enableVideo];
AgoraVideoEncoderConfiguration *encoderConfig = [[AgoraVideoEncoderConfiguration alloc] initWithSize:CGSizeMake(960, 540)
frameRate:(AgoraVideoFrameRateFps15)
bitrate:AgoraVideoBitrateStandard
orientationMode:(AgoraVideoOutputOrientationModeFixedPortrait)
mirrorMode:(AgoraVideoMirrorModeAuto)];
[self.agoraKit setVideoEncoderConfiguration:encoderConfig];
// set up local video to render your local camera preview
AgoraRtcVideoCanvas *videoCanvas = [[AgoraRtcVideoCanvas alloc] init];
videoCanvas.uid = 0;
// the view to be binded
videoCanvas.view = self.localView.videoView;
videoCanvas.renderMode = AgoraVideoRenderModeHidden;
[self.agoraKit setupLocalVideo:videoCanvas];
// you have to call startPreview to see local video
[self.agoraKit startPreview];
// Set audio route to speaker
[self.agoraKit setEnableSpeakerphone:YES];
// 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
AgoraRtcChannelMediaOptions *options = [[AgoraRtcChannelMediaOptions alloc] init];
options.autoSubscribeAudio = YES;
options.autoSubscribeVideo = YES;
options.publishCameraTrack = YES;
options.publishMicrophoneTrack = YES;
options.clientRoleType = AgoraClientRoleBroadcaster;
[[NetworkManager shared] generateTokenWithChannelName:channelName uid:0 success:^(NSString * _Nullable token) {
int result = [self.agoraKit joinChannelByToken:token channelId:channelName uid:0 mediaOptions:options joinSuccess:nil];
if (result != 0) {
// Usually happens with invalid parameters
// Error code description can be found at:
// en: https://api-ref.agora.io/en/video-sdk/ios/4.x/documentation/agorartckit/agoraerrorcode
// cn: https://doc.shengwang.cn/api-ref/rtc/ios/error-code
NSLog(@"joinChannel call failed: %d, please check your params", result);
}
}];
}
- (IBAction)onSendPress:(UIButton *)sender {
NSString *message = self.messageField.text;
if (message == nil || message.length <= 0) {
return;
}
NSInteger streamId = 0;
// create the data stream
// Each user can create up to five data streams during the lifecycle of the agoraKit
AgoraDataStreamConfig * config = [[AgoraDataStreamConfig alloc] init];
int result = [self.agoraKit createDataStream:&streamId config:config];
if (result != 0) {
[self showAlertWithTitle:@"Error" message:[NSString stringWithFormat:@"createDataStream call failed: %d, please check your params", result]];
return;
}
int sendResult = [self.agoraKit sendStreamMessage:streamId data:[message dataUsingEncoding:NSUTF8StringEncoding]];
if (sendResult != 0) {
[self showAlertWithTitle:@"Error" message:[NSString stringWithFormat:@"sendStreamMessage call failed: %d, please check your params", sendResult]];
} else {
self.messageField.text = nil;
}
}
- (void)viewDidDisappear:(BOOL)animated {
[super viewDidDisappear:animated];
[self.agoraKit disableAudio];
[self.agoraKit disableVideo];
[self.agoraKit stopPreview];
[self.agoraKit leaveChannel:nil];
[AgoraRtcEngineKit destroy];
}
/// callback when error occured for agora sdk, you are recommended to display the error descriptions on demand
/// to let user know something wrong is happening
/// Error code description can be found at:
/// en: https://api-ref.agora.io/en/video-sdk/ios/4.x/documentation/agorartckit/agoraerrorcode
/// cn: https://doc.shengwang.cn/api-ref/rtc/ios/error-code
/// @param errorCode error code of the problem
- (void)rtcEngine:(AgoraRtcEngineKit *)engine didOccurError:(AgoraErrorCode)errorCode {
[LogUtil log:[NSString stringWithFormat:@"Error %ld occur",errorCode] level:(LogLevelError)];
}
- (void)rtcEngine:(AgoraRtcEngineKit *)engine didJoinChannel:(NSString *)channel withUid:(NSUInteger)uid elapsed:(NSInteger)elapsed {
[LogUtil log:[NSString stringWithFormat:@"Join %@ with uid %lu elapsed %ldms", channel, uid, elapsed] level:(LogLevelDebug)];
self.localView.uid = uid;
}
/// callback when a remote user is joinning the channel, note audience in live broadcast mode will NOT trigger this event
/// @param uid uid of remote joined user
/// @param elapsed time elapse since current sdk instance join the channel in ms
- (void)rtcEngine:(AgoraRtcEngineKit *)engine didJoinedOfUid:(NSUInteger)uid elapsed:(NSInteger)elapsed {
[LogUtil log:[NSString stringWithFormat:@"remote user join: %lu %ldms", uid, elapsed] level:(LogLevelDebug)];
// Only one remote video view is available for this
// tutorial. Here we check if there exists a surface
// view tagged as this uid.
AgoraRtcVideoCanvas *videoCanvas = [[AgoraRtcVideoCanvas alloc]init];
videoCanvas.uid = uid;
// the view to be binded
videoCanvas.view = self.remoteView.videoView;
videoCanvas.renderMode = AgoraVideoRenderModeHidden;
[self.agoraKit setupRemoteVideo:videoCanvas];
self.remoteView.uid = uid;
}
/// callback when a remote user is leaving the channel, note audience in live broadcast mode will NOT trigger this event
/// @param uid uid of remote joined user
/// @param reason reason why this user left, note this event may be triggered when the remote user
/// become an audience in live broadcasting profile
- (void)rtcEngine:(AgoraRtcEngineKit *)engine didOfflineOfUid:(NSUInteger)uid reason:(AgoraUserOfflineReason)reason {
// to unlink your view from sdk, so that your view reference will be released
// note the video will stay at its last frame, to completely remove it
// you will need to remove the EAGL sublayer from your binded view
AgoraRtcVideoCanvas *videoCanvas = [[AgoraRtcVideoCanvas alloc]init];
videoCanvas.uid = uid;
// the view to be binded
videoCanvas.view = nil;
[self.agoraKit setupRemoteVideo:videoCanvas];
self.remoteView.uid = 0;
[LogUtil log:[NSString stringWithFormat:@"remote user left: %lu", uid] level:(LogLevelDebug)];
}
- (void)rtcEngine:(AgoraRtcEngineKit *)engine receiveStreamMessageFromUid:(NSUInteger)uid streamId:(NSInteger)streamId data:(NSData *)data {
NSString *message = [[NSString alloc] initWithData:data encoding:(NSUTF8StringEncoding)];
[LogUtil log: [NSString stringWithFormat:@"receiveStreamMessageFromUid: %lu message: %@", uid, message]];
[self showAlertWithTitle:[NSString stringWithFormat:@"from: %lu message: %@",uid, message]];
}
- (void)rtcEngine:(AgoraRtcEngineKit *)engine didOccurStreamMessageErrorFromUid:(NSUInteger)uid streamId:(NSInteger)streamId error:(NSInteger)error missed:(NSInteger)missed cached:(NSInteger)cached {
[LogUtil log: [NSString stringWithFormat:@"didOccurStreamMessageErrorFromUid: %lu error: %ld missed: %ld cached: %ld", uid, error, missed, cached]];
[self showAlertWithTitle:[NSString stringWithFormat:@"didOccurStreamMessageErrorFromUid: %lu",uid]];
}
@end