### Android Single Call Setup and Event Handling (Java) Source: https://context7.com/netease-kit/necallkit_doc_source/llms.txt Demonstrates initializing the CallKit engine in Android for single calls without a default UI. It covers setting up the engine, registering listeners for call events like receiving invitations, call connection, and call termination, and includes example code for handling these callbacks. Dependencies include the CallKit SDK. Input is via configuration objects and event data; output is through UI updates and log messages. ```java // Step 1: Initialize base CallKit (no UI) NESetupConfig config = new NESetupConfig.Builder("your_rtc_appkey") .rtcOption(new NERtcOption()) .build(); NECallEngine.sharedInstance().setup(this, config); // Step 2: Add call event listeners NECallEngine.sharedInstance().addCallDelegate(new NECallEngineDelegateAbs() { @Override public void onReceiveInvited(NEInviteInfo info) { // Received incoming call String callerAccId = info.getCallerAccId(); String callType = info.getCallType(); // AUDIO or VIDEO String channelId = info.getChannelId(); // Show your custom incoming call UI } @Override public void onCallConnected(NECallInfo callInfo) { // Call connected successfully // Setup remote video view if video call } @Override public void onCallEnd(NECallEndInfo endInfo) { // Call ended int reasonCode = endInfo.getReasonCode(); String message = endInfo.getMessage(); // Handle call end: 0=normal, 2=timeout, 3=busy, 11=canceled, 13=rejected, etc. } }); // Step 3: Caller initiates call NECallParam param = new NECallParam.Builder("callee_account_id") .callType(NECallType.VIDEO) .extraInfo("custom_data") // Optional custom data .build(); NECallEngine.sharedInstance().call(param, new NEResultObserver>() { @Override public void onResult(CommonResult result) { if (result.isSuccessful()) { NECallInfo callInfo = result.data; // Setup local video view NERtcVideoView localView = findViewById(R.id.local_view); NECallEngine.sharedInstance().setupLocalView(localView); } else { Log.e("Call", "Failed: " + result.code + " - " + result.msg); } } }); // Step 4: Callee accepts call NECallEngine.sharedInstance().accept(new NEResultObserver>() { @Override public void onResult(CommonResult result) { if (result.isSuccessful()) { // Setup video views NERtcVideoView localView = findViewById(R.id.local_view); NERtcVideoView remoteView = findViewById(R.id.remote_view); NECallEngine.sharedInstance().setupLocalView(localView); NECallEngine.sharedInstance().setupRemoteView(remoteView); } } }); // Step 5: Hangup/reject/cancel call NEHangupParam hangupParam = new NEHangupParam("channelId", "reason"); NECallEngine.sharedInstance().hangup(hangupParam, new NEResultObserver>() { @Override public void onResult(CommonResult result) { if (result.isSuccessful()) { // Hangup successful, cleanup UI } } }); ``` -------------------------------- ### Android: Initialize NIM SDK and Start Video Call with UI Source: https://context7.com/netease-kit/necallkit_doc_source/llms.txt This snippet demonstrates how to initialize the NIM SDK and NECallKit UI, log in to IM, and then initiate a 1-on-1 video call on Android. It covers setting up SDK options, handling login callbacks, configuring CallKit UI options, and starting the call with specified parameters. ```java // Step 1: Initialize NIM SDK V10 SDKOptions sdkOptions = new SDKOptions(); NIMClient.initV2(context, sdkOptions); // Step 2: Login to IM NIMClient.getService(V2NIMLoginService.class).login("account_id", "token", null, new V2NIMSuccessCallback() { @Override public void onSuccess(Void unused) { // Login successful } }, new V2NIMFailureCallback() { @Override public void onFailure(V2NIMError error) { Log.e("Login", "Failed: " + error.getCode() + " - " + error.getDesc()); } } ); // Step 3: Initialize CallKit with UI CallKitUIOptions options = new CallKitUIOptions.Builder() .rtcAppKey("your_rtc_appkey") // Required: RTC AppKey from console .timeOutMillisecond(30 * 1000L) // Call timeout: 30 seconds .notificationConfigFetcher(neInviteInfo -> new CallKitNotificationConfig(R.drawable.ic_logo)) .resumeBGInvitation(true) // Auto-resume background calls .initRtcMode(NECallInitRtcMode.IN_NEED) // RTC init mode .build(); CallKitUI.init(getApplicationContext(), options); // Step 4: Start a video call CallParam param = new CallParam.Builder() .callType(NECallType.VIDEO) // Or NECallType.AUDIO for audio only .calledAccId("callee_account_id") // IM account of the callee .build(); CallKitUI.startSingleCall(getActivity(), param); // User B receives call, clicks accept button, and video call begins // Both users can hangup by clicking the hangup button ``` -------------------------------- ### React Web Single Call with UI Integration Source: https://context7.com/netease-kit/necallkit_doc_source/llms.txt Integrates Netease CallKit with React UI components for browser-based video calling. Requires installation of '@xkit-yx/call-kit-react-ui' and '@xkit-yx/call-kit'. Initializes NIM SDK and CallKit, then renders a CallViewProvider to manage call states and UI. ```tsx // Step 1: Install dependencies // npm install @xkit-yx/call-kit-react-ui @xkit-yx/call-kit // yarn add @xkit-yx/call-kit-react-ui @xkit-yx/call-kit // Step 2: Initialize IM SDK V10 and CallKit import React, { useEffect, useMemo, useRef } from 'react' import { CallViewProvider, CallViewProviderRef } from '@xkit-yx/call-kit-react-ui' import '@xkit-yx/call-kit-react-ui/es/style' import V2NIM from 'nim-web-sdk-ng' const appkey = 'your_appkey' const account = 'your_account_id' const token = 'your_token' const CallApp = () => { const [isLogin, setIsLogin] = React.useState(false) const callViewProviderRef = useRef(null) // Initialize NIM SDK const nim = useMemo(() => { return V2NIM.getInstance({ appkey, account, token, apiVersion: 'v2', debugLevel: 'debug', }) }, []) useEffect(() => { if (nim) { // Login when component mounts nim.V2NIMLoginService.login(account, token, { retryCount: 5, }).then(() => { setIsLogin(true) }).catch(error => { console.error('Login failed:', error) }) } // Logout when component unmounts return () => { if (nim) { nim.V2NIMLoginService.logout() setIsLogin(false) } } }, [nim]) // Step 3: Render CallViewProvider and make calls return nim && isLogin ? ( ) :
Loading...
} export default CallApp // Callee receives call notification UI automatically // Click accept to join the call, click hangup to end ``` -------------------------------- ### JavaScript Web Single Call without UI Source: https://context7.com/netease-kit/necallkit_doc_source/llms.txt Provides a headless implementation of Netease CallKit for custom UI designs. Requires installation of '@xkit-yx/call-kit'. This snippet covers initialization, making calls, setting up video views, handling incoming calls, managing call events, and ending calls. ```javascript // Step 1: Install and initialize // npm install @xkit-yx/call-kit import V2NIM from 'nim-web-sdk-ng' import { NECall } from '@xkit-yx/call-kit' const appkey = 'your_appkey' const account = 'your_account_id' const token = 'your_token' // Initialize NIM SDK V10 const nim = V2NIM.getInstance({ appkey, account, token, apiVersion: 'v2', debugLevel: 'debug', }) // Login to IM await nim.V2NIMLoginService.login(account, token) // Initialize CallKit const neCall = NECall.getInstance() neCall.setup({ nim, appkey, rtcConfig: { videoResolution: 'VIDEO_QUALITY_720p', videoFrameRate: 'CHAT_VIDEO_FRAME_RATE_NORMAL', audioQuality: 'speech_low_quality', } }) // Step 2: Make a call const calleeId = 'remote_account_id' neCall.call({ accId: calleeId, callType: '2', // '1' for audio, '2' for video }) // Setup video views const localView = document.getElementById('localView') const remoteView = document.getElementById('remoteView') neCall.setLocalView(localView) neCall.setRemoteView(remoteView) // Step 3: Handle incoming call neCall.on('onReceiveInvited', (inviteInfo) => { // Show custom incoming call UI console.log('Incoming call from:', inviteInfo.callerAccId) console.log('Call type:', inviteInfo.callType) // Setup views and accept const localView = document.getElementById('localView') const remoteView = document.getElementById('remoteView') neCall.setLocalView(localView) neCall.setRemoteView(remoteView) }) // Accept incoming call neCall.accept() // Step 4: Handle call events neCall.on('onCallConnected', () => { console.log('Call connected successfully') // Update UI to show in-call state }) // Switch call type (audio <-> video) neCall.switchCallType('2') // Switch to video // Control audio/video neCall.enableLocalVideo(true) // Enable/disable local video neCall.muteLocalAudio(false) // Mute/unmute local audio // Step 5: End call neCall.hangup() // Handle call end neCall.on('onCallEnd', (endInfo) => { const reason = endInfo.reasonCode // 0=normal, 2=timeout, 3=busy, 11=canceled, 13=rejected, etc. console.log('Call ended:', reason) // Cleanup UI }) // Handle call detail record neCall.on('onRecordSend', (record) => { // Call ended due to cancel/reject/timeout/busy // Update UI with call history }) ``` -------------------------------- ### Android Group Call Implementation Source: https://context7.com/netease-kit/necallkit_doc_source/llms.txt Enables multi-party video conferencing with participant management. Initializes CallKit with group call support, starts new group calls, and allows joining existing calls. Participants can manage their audio/video, and a host can manage the call. ```java import com.netease.yunxin.nertc.ui.CallKitUI; import com.netease.yunxin.nertc.ui.CallKitUIOptions; import com.netease.yunxin.nertc.ui.group.GroupCallParam; import com.netease.yunxin.nertc.ui.group.GroupJoinParam; import org.json.JSONObject; import java.util.ArrayList; import java.util.UUID; // Step 1: Enable group call in initialization CallKitUIOptions options = new CallKitUIOptions.Builder() .rtcAppKey("your_rtc_appkey") .timeOutMillisecond(30 * 1000L) .enableGroup(true) // Enable group call feature .contactSelector((context, groupId, existingMembers, resultObserver) -> { // Implement member selection UI // Return selected user list to resultObserver return null; }) .build(); CallKitUI.init(getApplicationContext(), options); // Step 2: Start a group call ArrayList callees = new ArrayList<>(); callees.add("user1_account_id"); callees.add("user2_account_id"); callees.add("user3_account_id"); JSONObject extraInfo = new JSONObject(); extraInfo.put("topic", "Team Meeting"); GroupCallParam param = new GroupCallParam.Builder() .callId(UUID.randomUUID().toString()) // Unique call ID .callees(callees) // List of participants .extraInfo(extraInfo.toString()) // Optional metadata .build(); CallKitUI.startGroupCall(this, param); // Step 3: Join an existing group call String callId = "existing_call_id"; // Received from invitation GroupJoinParam joinParam = new GroupJoinParam(callId); CallKitUI.joinGroupCall(this, joinParam); // Step 4: Invite members during call // contactSelector callback is triggered when user clicks "Add Member" // Implement UI to select additional users and return their account IDs // CallKit automatically sends invitations to selected users // All participants see each other's video streams // Each user can control their own audio/video // Host can manage participants and end the call for all ``` -------------------------------- ### Configure Video and Audio Settings in Java Source: https://context7.com/netease-kit/necallkit_doc_source/llms.txt This Java code snippet demonstrates how to configure custom video resolution, frame rate, audio profile, and audio scenario during the initialization of the NE Calls SDK. It utilizes NERtcCallExtension to override methods for pre-join configuration. Dependencies include the NE Calls SDK and its associated RTC components. ```java NESetupConfig config = new NESetupConfig.Builder("your_rtc_appkey") .rtcCallExtension(new NERtcCallExtension() { @Override protected void configAudioProfileBeforeJoin() { // Audio configuration: standard quality + speech scenario NERtcEx.getInstance().setAudioProfile( NERtcConstants.AudioProfile.STANDARD, NERtcConstants.AudioScenario.SPEECH ); } @Override protected void configVideoConfigBeforeJoin() { NERtcVideoConfig videoConfig = new NERtcVideoConfig(); // Set frame rate: 15 FPS videoConfig.frameRate = NERtcEncodeConfig.NERtcVideoFrameRate.FRAME_RATE_FPS_15; // Set resolution: 640x360 (width must be larger than height) videoConfig.width = 640; videoConfig.height = 360; NERtcEx.getInstance().setLocalVideoConfig(videoConfig); } @Override protected void configChannelProfileBeforeJoin() { // Set channel profile for communication NERtcEx.getInstance().setChannelProfile( NERtcConstants.RTCChannelProfile.COMMUNICATION ); } }) .build(); NECallEngine.sharedInstance().setup(this, config); ``` -------------------------------- ### iOS Quick Call Integration (Objective-C) Source: https://context7.com/netease-kit/necallkit_doc_source/llms.txt Provides a streamlined approach for integrating video and audio calling features into iOS applications. This snippet demonstrates the initialization of both the NIM SDK and the CallKit SDK, followed by user login and initiating a call. It relies on the NIM SDK for core IM functionalities and CallKit for call management. The UI aspects, such as receiving calls and call controls, are handled automatically by the CallKit UI components. ```objectivec // Step 1: Initialize NIM SDK #import NIMSDKOption *option = [NIMSDKOption optionWithAppKey:@"your_appkey"]; option.apnsCername = @"your_apns_certificate"; V2NIMSDKOption *v2Option = [[V2NIMSDKOption alloc] init]; v2Option.useV1Login = NO; // Use V10 login API [[NIMSDK sharedSDK] registerWithOptionV2:option v2Option:v2Option]; // Step 2: Login to IM [[NIMSDK sharedSDK].v2LoginService login:@"account_id" token:@"token" option:nil success:^{ NSLog(@"Login successful"); } failure:^(V2NIMError * _Nonnull error) { NSLog(@"Login failed: %@", error); }]; // Step 3: Initialize CallKit #import NESetupConfig *setupConfig = [[NESetupConfig alloc] initWithAppkey:@"your_rtc_appkey"]; [[NECallEngine sharedInstance] setup:setupConfig]; NECallUIKitConfig *config = [[NECallUIKitConfig alloc] init]; [[NERtcCallUIKit sharedInstance] setupWithConfig:config]; // Step 4: Make a call NEUICallParam *callParam = [[NEUICallParam alloc] init]; callParam.currentUserAccid = @"current_user_account_id"; callParam.remoteUserAccid = @"remote_account_id"; callParam.remoteShowName = @"Remote User Name"; // NECallType.audio for audio call, NECallType.video for video call [[NERtcCallUIKit sharedInstance] callWithParam:callParam withCallType:NECallType.video]; // Callee receives call notification and UI automatically appears // Click accept to start the call, click hangup to end ``` -------------------------------- ### Handle Call Failure During Initiation (Java) Source: https://context7.com/netease-kit/necallkit_doc_source/llms.txt This code shows how to use `NEResultObserver` to handle errors when initiating a call. It checks the success status of the `CommonResult` and provides specific error messages for common HTTP error codes like 408 (timeout) and 403 (permission denied), along with a general error message. ```java NECallEngine.sharedInstance().call(param, new NEResultObserver>() { @Override public void onResult(CommonResult result) { if (!result.isSuccessful()) { int errorCode = result.code; String errorMsg = result.msg; // Handle specific error codes if (errorCode == 408) { showError("Request timeout"); } else if (errorCode == 403) { showError("Permission denied"); } else { showError("Call failed: " + errorMsg); } } } }); ``` -------------------------------- ### Android AI Real-time Translation Source: https://context7.com/netease-kit/necallkit_doc_source/llms.txt Integrates live call translation with multi-language support. Requires purchasing an AI service and enabling transcription via a server API. Displays translated text in a subtitle UI component or through a custom callback. ```java // Prerequisites: // 1. Purchase AI service from NetEase console // 2. Subscribe to call status on your backend server // 3. When call status changes to "connected", enable AI transcription via server API // Step 1: Add subtitle UI component (pre-built) // In your call activity layout XML: // // Component automatically listens for subtitle events // Step 2: Or implement custom subtitle handling import com.netease.lava.nertc.NERtcCallbackEx; import com.netease.lava.nertc.NERtcEx; import com.netease.lava.nertc.NERtcASRCaptionConfig; import com.netease.lava.nertc.model.NERtcAsrCaptionResult; // ... inside your class NECallEngine.sharedInstance().setRtcCallback(new NERtcCallbackEx() { @Override public void onAsrCaptionResult( NERtcAsrCaptionResult[] result, int resultCount ) { if (result != null) { for (NERtcAsrCaptionResult ret : result) { if (ret.isFinal && isShowTranslation == ret.haveTranslation) { // Get translated text String text = isShowTranslation ? ret.translatedText : ret.content; long uid = ret.uid; boolean hasTranslation = ret.haveTranslation; // Get speaker name String accId = NECallEngine.sharedInstance() .getUserWithRtcUid(uid).getAccId(); // Display subtitle in your UI updateSubtitleUI(accId, text); } } } } }); // Step 3: Enable AI translation during call NERtcASRCaptionConfig config = new NERtcASRCaptionConfig(); config.dstLanguageArr = new String[]{"en", "zh"}; // Target languages NERtcEx.getInstance().startASRCaption(config); // Step 4: Disable AI translation NERtcEx.getInstance().stopASRCaption(); // Translation flows: Audio -> AI Server -> Translation -> Client // Supports multiple languages: Chinese, English, Japanese, Korean, etc. // Real-time display with minimal latency ``` -------------------------------- ### Handle Call End with Error Information (Java) Source: https://context7.com/netease-kit/necallkit_doc_source/llms.txt This snippet demonstrates how to implement the `NECallEngineDelegateAbs` to handle call end events. It processes various `reasonCode` values from `NECallEndInfo` to provide specific user feedback or logging, and includes a placeholder for UI cleanup. ```java NECallEngine.sharedInstance().addCallDelegate(new NECallEngineDelegateAbs() { @Override public void onCallEnd(NECallEndInfo endInfo) { int reasonCode = endInfo.getReasonCode(); String message = endInfo.getMessage(); String extraInfo = endInfo.getExtraString(); switch (reasonCode) { case NEHangupReasonCode.NORMAL: // 0 // Call ended normally showToast("Call ended"); break; case NEHangupReasonCode.TOKEN_ERROR: // 1 // RTC token error showError("Authentication failed"); break; case NEHangupReasonCode.TIME_OUT: // 2 // Call timeout (no answer) showToast("No answer"); break; case NEHangupReasonCode.BUSY: // 3 // User is busy (in another call) showToast("User is busy"); break; case NEHangupReasonCode.RTC_INIT_ERROR: // 4 // RTC initialization failed showError("Connection failed"); break; case NEHangupReasonCode.JOIN_RTC_ERROR: // 5 // Failed to join RTC channel showError("Failed to connect"); break; case NEHangupReasonCode.CALLER_CANCEL: // 11 // Caller canceled the call showToast("Call canceled"); break; case NEHangupReasonCode.CALLEE_CANCELED: // 12 // Call was canceled by caller showToast("Call canceled by caller"); break; case NEHangupReasonCode.CALLEE_REJECT: // 13 // You rejected the call showToast("Call rejected"); break; case NEHangupReasonCode.CALLER_REJECTED: // 14 // Call was rejected showToast("Call rejected by user"); break; case NEHangupReasonCode.HANG_UP: // 15 // You hung up the call showToast("Call ended"); break; case NEHangupReasonCode.BE_HUNG_UP: // 16 // Other party hung up showToast("Call ended by other party"); break; case NEHangupReasonCode.OTHER_REJECTED: // 17 // Rejected by another device (multi-device login) showToast("Rejected on another device"); break; case NEHangupReasonCode.OTHER_ACCEPTED: // 18 // Accepted on another device (multi-device login) showToast("Answered on another device"); break; default: showError("Call ended: " + message); } // Cleanup call UI finishCallActivity(); } }); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.