
在开始react native客户端开发之前,必须在voximplant控制面板中进行必要的配置。这包括设置一个voxengine场景和相应的路由规则,以确保通话能够正确地被处理和路由。
VoxEngine场景是Voximplant平台上的JavaScript代码,用于处理和控制通话逻辑。对于简单的点对点语音通话,我们需要一个场景来将呼叫从发起方路由到接收方。
示例VoxEngine场景代码:
// This scenario handles incoming calls to the Voximplant application.
VoxEngine.addEventListener(AppEvents.CallAlerting, (e) => {
// e.call represents the incoming call object.
// e.destination is the target username for the call.
// Create a new call to the destination user directly.
const newCall = VoxEngine.callUserDirect(
e.call, // The original incoming call
e.destination, // The target user (e.g., "testuser2")
{
// Optional: Pass display name, caller ID, and custom headers
displayName: e.displayName,
callerid: e.callerid,
headers: e.headers,
}
);
// Use easyProcess to link the two calls (incoming and outgoing)
// This handles media forwarding and call state synchronization.
// The third argument is for custom handling when the call is connected (empty here).
// The fourth argument (true) indicates that the original call should be rejected if newCall fails.
VoxEngine.easyProcess(e.call, newCall, () => {}, true);
});此场景监听 AppEvents.CallAlerting 事件,该事件在Voximplant应用程序收到呼叫时触发。它会创建一个新的呼叫,直接路由到目标用户,并使用 VoxEngine.easyProcess 简化了两个呼叫之间的媒体和状态管理。
路由规则将呼叫与您的VoxEngine场景关联起来。为了实现任意用户之间的呼叫,建议使用一个通配符路由规则。
在React Native应用中,我们将实现用户登录、发起呼叫和处理来电的功能。
用户需要通过Voximplant SDK登录到平台才能发起或接收呼叫。登录功能通常包含连接到Voximplant服务和进行身份验证两个步骤。
登录屏幕示例代码:
import React, { useState } from 'react';
import {
SafeAreaView,
View,
TextInput,
TouchableOpacity,
Text,
Alert,
StatusBar,
StyleSheet,
} from 'react-native';
import { useNavigation } from '@react-navigation/native';
import { Voximplant } from 'react-native-voximplant';
// 替换为您的Voximplant应用和账户信息
const VOXIMPLANT_APP = 'YOUR_APP_NAME'; // 例如:'mychatapp'
const VOXIMPLANT_ACCOUNT = 'YOUR_ACCOUNT_NAME'; // 例如:'yourcompany'
const LoginScreen = () => {
const navigation = useNavigation();
const voximplant = Voximplant.getInstance();
const [user, setUser] = useState('');
const [password, setPassword] = useState('');
async function login() {
try {
// 检查客户端连接状态
let clientState = await voximplant.getClientState();
// 如果未连接,则先连接到Voximplant服务
if (clientState === Voximplant.ClientState.DISCONNECTED) {
await voximplant.connect();
}
// 执行登录操作
// 用户名格式为:username@app_name.account_name.voximplant.com
await voximplant.login(
`${user}@${VOXIMPLANT_APP}.${VOXIMPLANT_ACCOUNT}.voximplant.com`,
password,
);
// 登录成功,导航到呼叫屏幕
navigation.navigate('CallScreen');
} catch (e) {
let message;
switch (e.name) {
case Voximplant.ClientEvents.ConnectionFailed:
message = '连接错误,请检查您的网络连接';
break;
case Voximplant.ClientEvents.AuthResult:
message = convertAuthCodeMessage(e.code);
break;
default:
message = '未知错误,请重试';
}
showLoginError(message);
}
}
// 辅助函数:将Voximplant认证错误码转换为用户友好的消息
function convertAuthCodeMessage(code) {
switch (code) {
case 401:
return '密码无效';
case 404:
return '用户不存在';
case 491:
return '状态无效';
default:
return '请稍后重试';
}
}
// 辅助函数:显示登录错误弹窗
function showLoginError(message) {
Alert.alert('登录错误', message, [{ text: '确定' }]);
}
return (
<SafeAreaView style={styles.safearea}>
<StatusBar barStyle="dark-content" />
<View style={styles.container}>
<TextInput
style={styles.forminput}
placeholder="用户名"
autoCapitalize="none"
autoCorrect={false}
onChangeText={setUser}
/>
<TextInput
style={styles.forminput}
placeholder="密码"
secureTextEntry={true}
onChangeText={setPassword}
/>
<TouchableOpacity onPress={login} style={styles.button}>
<Text style={styles.textButton}>登录</Text>
</TouchableOpacity>
</View>
</SafeAreaView>
);
};
const styles = StyleSheet.create({
safearea: { flex: 1, backgroundColor: '#fff' },
container: { flex: 1, justifyContent: 'center', alignItems: 'center', padding: 20 },
forminput: {
width: '80%',
height: 50,
borderColor: '#ccc',
borderWidth: 1,
borderRadius: 5,
paddingHorizontal: 15,
marginBottom: 15,
},
button: {
backgroundColor: '#007bff',
paddingVertical: 12,
paddingHorizontal: 30,
borderRadius: 5,
},
textButton: {
color: '#fff',
fontSize: 16,
fontWeight: 'bold',
},
});
export default LoginScreen;注意事项:
用户登录成功后,可以通过 Voximplant.getInstance().call() 方法发起语音通话。为了实现纯语音通话,需要将 callSettings 中的视频相关选项设置为 false。
发起呼叫示例代码:
import { Voximplant } from 'react-native-voximplant';
// ... 其他组件代码
const makeVoiceCall = async (destinationUsername) => {
const client = Voximplant.getInstance();
try {
// 配置通话设置,禁用视频以进行纯语音通话
let callSettings = {
video: {
sendVideo: false, // 不发送视频
receiveVideo: false, // 不接收视频
},
// 其他可选设置,例如:
// extraHeaders: { 'X-Custom-Header': 'value' },
};
// 发起呼叫到指定用户
// destinationUsername 应该是Voximplant平台上的有效用户名,例如 "testuser2"
const call = await client.call(destinationUsername, callSettings);
console.log(`Calling ${destinationUsername}... Call ID: ${call.callId}`);
// 订阅呼叫事件以管理呼叫状态
subscribeToCallEvents(call);
// 返回呼叫对象,以便在UI中进行管理(例如,挂断按钮)
return call;
} catch (e) {
console.error('Error making call:', e);
Alert.alert('呼叫失败', e.message || '无法发起呼叫');
return null;
}
};
// 辅助函数:订阅呼叫事件
const subscribeToCallEvents = (call) => {
call.addEventListener(Voximplant.CallEvents.Connected, (callEvent) => {
console.log('Call Connected:', callEvent.callId);
Alert.alert('通话状态', '已连接');
// 更新UI,显示通话已连接
});
call.addEventListener(Voximplant.CallEvents.Disconnected, (callEvent) => {
console.log('Call Disconnected:', callEvent.callId);
Alert.alert('通话状态', '已挂断');
// 更新UI,显示通话已结束,并清理资源
});
call.addEventListener(Voximplant.CallEvents.Failed, (callEvent) => {
console.log('Call Failed:', callEvent.callId, callEvent.reason);
Alert.alert('通话失败', callEvent.reason || '呼叫未能建立');
// 更新UI,显示通话失败信息
});
// 还可以订阅其他事件,如 Muted, Unmuted, Hold, etc.
};
// 在您的CallScreen组件中,可以这样调用:
// const call = await makeVoiceCall("testuser2");
// 如果需要挂断,可以调用 call.hangup();关键点:
当其他用户呼叫当前登录的用户时,Voximplant客户端会触发 Voximplant.ClientEvents.IncomingCall 事件。你需要监听此事件并处理来电。
处理来电示例代码:
import { useEffect, useRef } from 'react';
import { Voximplant } from 'react-native-voximplant';
import { Alert } from 'react-native';
const IncomingCallHandler = () => {
const voximplant = Voximplant.getInstance();
const currentCall = useRef(null); // 用于存储当前活跃的呼叫对象
useEffect(() => {
// 注册来电监听器
const incomingCallListener = (callEvent) => {
console.log('Incoming Call:', callEvent.call.callId);
const incomingCall = callEvent.call;
currentCall.current = incomingCall; // 保存来电对象
// 订阅来电的事件
incomingCall.addEventListener(Voximplant.CallEvents.Connected, (e) => {
console.log('Incoming Call Connected:', e.callId);
Alert.alert('来电状态', '已接通');
// 更新UI,显示通话已连接
});
incomingCall.addEventListener(Voximplant.CallEvents.Disconnected, (e) => {
console.log('Incoming Call Disconnected:', e.callId);
Alert.alert('来电状态', '已挂断');
currentCall.current = null; // 清理
// 更新UI,显示通话已结束
});
incomingCall.addEventListener(Voximplant.CallEvents.Failed, (e) => {
console.log('Incoming Call Failed:', e.callId, e.reason);
Alert.alert('来电失败', e.reason || '来电未能建立');
currentCall.current = null; // 清理
// 更新UI,显示来电失败信息
});
incomingCall.addEventListener(Voximplant.CallEvents.EndpointAdded, (e) => {
console.log('Endpoint Added:', e.endpoint.displayName);
// 处理端点(例如,显示参与者列表)
});
Alert.alert(
'来电',
`来自 ${callEvent.call.getEndpoints()[0]?.displayName || callEvent.call.callId} 的呼叫`,
[
{
text: '拒接',
onPress: () => {
incomingCall.decline(); // 拒接来电
currentCall.current = null;
},
style: 'cancel',
},
{
text: '接听',
onPress: async () => {
try {
await incomingCall.answer(); // 接听来电
console.log('Call Answered:', incomingCall.callId);
// 导航到通话界面或更新UI
} catch (e) {
console.error('Error answering call:', e);
Alert.alert('接听失败', e.message || '无法接听');
}
},
},
],
{ cancelable: false },
);
};
voximplant.addEventListener(Voximplant.ClientEvents.IncomingCall, incomingCallListener);
// 组件卸载时移除监听器
return () => {
voximplant.removeEventListener(Voximplant.ClientEvents.IncomingCall, incomingCallListener);
if (currentCall.current) {
currentCall.current.hangup(); // 确保在卸载时挂断任何活跃呼叫
}
};
}, []); // 仅在组件挂载和卸载时运行
return null; // 此组件不渲染任何UI,仅用于处理逻辑
};
export default IncomingCallHandler;
// 您可以在App.js或主导航堆栈中包含此组件,以全局处理来电
// 例如:
// <IncomingCallHandler />关键点:
通过遵循上述步骤和注意事项,您将能够在React Native应用中成功集成Voximplant,实现稳定可靠的语音通话功能。
以上就是在React Native中集成Voximplant实现语音通话功能的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号