首页 > web前端 > js教程 > 正文

在React Native中集成Voximplant实现语音通话功能

花韻仙語
发布: 2025-10-07 14:03:01
原创
563人浏览过

在React Native中集成Voximplant实现语音通话功能

本教程详细介绍了如何在React Native应用中集成Voximplant,实现端到端的语音通话功能。内容涵盖Voximplant控制面板的必要配置,包括VoxEngine场景和路由规则的设置,以及React Native客户端的用户登录、发起语音通话和处理来电的实现步骤。通过清晰的代码示例和注意事项,帮助开发者快速构建稳定的语音通话应用。

1. Voximplant平台配置

在开始react native客户端开发之前,必须在voximplant控制面板中进行必要的配置。这包括设置一个voxengine场景和相应的路由规则,以确保通话能够正确地被处理和路由。

1.1 创建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 简化了两个呼叫之间的媒体和状态管理。

1.2 配置路由规则

路由规则将呼叫与您的VoxEngine场景关联起来。为了实现任意用户之间的呼叫,建议使用一个通配符路由规则。

  • 路由模式: .*
    • 这个模式意味着匹配任何数量的任何字符,从而确保所有针对您的Voximplant应用程序的呼叫都将由您指定的VoxEngine场景处理。
  • 关联场景: 将此路由规则与您刚刚创建的VoxEngine场景关联。

2. React Native客户端实现

在React Native应用中,我们将实现用户登录、发起呼叫和处理来电的功能。

2.1 用户登录

用户需要通过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;
登录后复制

注意事项:

千图设计室AI海报
千图设计室AI海报

千图网旗下的智能海报在线设计平台

千图设计室AI海报 172
查看详情 千图设计室AI海报
  • 请将 VOXIMPLANT_APP 和 VOXIMPLANT_ACCOUNT 替换为你在Voximplant控制面板中创建的实际应用名称和账户名称。
  • 确保在Voximplant控制面板中创建了用于测试的用户(例如 testuser1 和 testuser2)。

2.2 发起语音通话

用户登录成功后,可以通过 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();
登录后复制

关键点:

  • client.call("testuser2", callSettings):这里 testuser2 是你希望呼叫的Voximplant用户。
  • callSettings.video:设置为 false 确保这是一个纯语音呼叫。
  • 订阅呼叫事件: 这是至关重要的一步。你需要监听 Connected、Disconnected 和 Failed 等事件,以便在UI中准确反映通话状态并处理通话生命周期。

2.3 处理来电

当其他用户呼叫当前登录的用户时,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 />
登录后复制

关键点:

  • voximplant.addEventListener(Voximplant.ClientEvents.IncomingCall, incomingCallListener):注册一个监听器来捕获所有传入的呼叫。
  • incomingCall.answer():接听来电。
  • incomingCall.decline():拒接来电。
  • incomingCall.hangup():挂断已接通的电话。
  • 同样,为来电对象订阅 Connected、Disconnected 和 Failed 事件,以管理来电的生命周期。
  • 在实际应用中,来电通常会触发一个独立的“来电屏幕”或通知,允许用户选择接听或拒接。

3. 总结与注意事项

  • 平台配置是基础: 确保Voximplant控制面板中的VoxEngine场景和路由规则配置正确无误,这是所有客户端功能正常运行的前提。
  • 用户认证: 客户端必须成功登录Voximplant平台才能发起或接收呼叫。
  • 呼叫事件监听: 无论是发起呼叫还是处理来电,都必须订阅呼叫对象(Call)的事件(如 Connected, Disconnected, Failed),以便准确更新UI和管理通话状态。
  • UI/UX设计: 本教程侧重于核心功能实现,实际应用中,您需要为登录、拨号、通话中和来电状态设计合适的UI界面和用户体验。
  • 错误处理: 始终实现健壮的错误处理机制,以应对网络问题、认证失败或通话建立失败等情况。
  • 权限管理: 在React Native中,您需要确保应用已获得麦克风权限(如果涉及视频,还需要摄像头权限)。这通常通过 react-native-permissions 等库进行管理。
  • 参考官方示例: Voximplant官方的React Native demo(例如 react-native-demo/CallApp/src/CallScreen.js)提供了更完整的呼叫屏幕实现,包括媒体控制(静音、扬声器)、视频切换等功能,是进一步学习和优化的宝贵资源。

通过遵循上述步骤和注意事项,您将能够在React Native应用中成功集成Voximplant,实现稳定可靠的语音通话功能。

以上就是在React Native中集成Voximplant实现语音通话功能的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号