npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

react-native-coze-socket

v1.1.0

Published

React Native wrapper for Gizwits Coze Socket SDK

Readme

React Native Coze Socket SDK 使用文档

简介

React Native Coze Socket SDK 是 Gizwits Coze Socket SDK 的 React Native 封装,提供了在 React Native 应用中使用实时语音通信功能的能力。该模块支持实时语音录制、传输、播放以及字幕显示功能,现已完全支持 TypeScript。

功能特点

  • 实时语音录制和传输
  • 高质量音频播放
  • 实时字幕显示
  • 完整的会话管理
  • 简单易用的 API
  • 事件监听机制
  • 完整的 TypeScript 类型支持

安装

npm install react-native-coze-socket --save

或者使用 yarn:

yarn add react-native-coze-socket

Android 配置

确保在 android/app/build.gradle 文件中设置了正确的 minSdkVersion:

android {
    defaultConfig {
        minSdkVersion 23
        // 其他配置...
    }
    // 其他配置...
}

AndroidManifest.xml 中添加必要的权限:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />

基本用法

导入模块

import CozeSocket from 'react-native-coze-socket';

初始化 SDK

在组件挂载时初始化 SDK:

useEffect(() => {
  const initializeSDK = async () => {
    try {
      await CozeSocket.initialize();
      console.log('Coze SDK 初始化成功');
    } catch (error) {
      console.error('Coze SDK 初始化失败:', error);
    }
  };

  initializeSDK();

  // 组件卸载时清理资源
  return () => {
    CozeSocket.release();
  };
}, []);

设置事件监听器

useEffect(() => {
  // 设置事件监听器
  const webSocketOpenSubscription = CozeSocket.addListener('onWebSocketOpen', (data) => {
    console.log('WebSocket已连接:', data.message);
  });

  const subtitleSubscription = CozeSocket.addListener('onSubtitleReceived', (data) => {
    console.log('收到字幕:', data.content);
    // 更新UI显示字幕
  });

  const errorSubscription = CozeSocket.addListener('onError', (data) => {
    console.error('错误:', data.message);
  });

  // 组件卸载时移除监听器
  return () => {
    CozeSocket.removeListener('onWebSocketOpen', webSocketOpenSubscription);
    CozeSocket.removeListener('onSubtitleReceived', subtitleSubscription);
    CozeSocket.removeListener('onError', errorSubscription);
    // 或者一次性移除所有监听器
    // CozeSocket.removeAllListeners();
  };
}, []);

录音和播放

开始录音

const startRecording = async () => {
  try {
    const success = await CozeSocket.startRecord();
    if (success) {
      console.log('开始录音成功');
    } else {
      console.log('开始录音失败');
    }
  } catch (error) {
    console.error('开始录音错误:', error);
  }
};

结束录音

const stopRecording = async () => {
  try {
    const success = await CozeSocket.endRecord();
    if (success) {
      console.log('结束录音成功');
    } else {
      console.log('结束录音失败');
    }
  } catch (error) {
    console.error('结束录音错误:', error);
  }
};

取消会话

const cancelCurrentChat = async () => {
  try {
    await CozeSocket.cancelChat();
    console.log('会话已取消');
  } catch (error) {
    console.error('取消会话错误:', error);
  }
};

清除缓冲区

const clearAudioBuffers = async () => {
  try {
    await CozeSocket.clearBuffers();
    console.log('缓冲区已清除');
  } catch (error) {
    console.error('清除缓冲区错误:', error);
  }
};

完整示例

以下是一个完整的示例,展示了如何在 React Native 应用中使用 Coze Socket SDK:

import React, { useEffect, useState } from 'react';
import { View, Text, TouchableOpacity, StyleSheet, Alert } from 'react-native';
import CozeSocket from 'react-native-coze-socket';

const CozeVoiceChat = () => {
  const [isListening, setIsListening] = useState(false);
  const [subtitle, setSubtitle] = useState('');
  const [isConnected, setIsConnected] = useState(false);

  useEffect(() => {
    // 初始化SDK
    const initializeSDK = async () => {
      try {
        await CozeSocket.initialize();
        console.log('Coze SDK 初始化成功');
      } catch (error) {
        console.error('Coze SDK 初始化失败:', error);
        Alert.alert('错误', '初始化失败: ' + error.message);
      }
    };

    // 设置事件监听器
    const setupListeners = () => {
      // WebSocket连接事件
      CozeSocket.addListener('onWebSocketOpen', (data) => {
        console.log('WebSocket已连接:', data.message);
        setIsConnected(true);
      });

      CozeSocket.addListener('onWebSocketError', (data) => {
        console.error('WebSocket错误:', data.error);
        Alert.alert('连接错误', data.error);
      });

      // 字幕事件
      CozeSocket.addListener('onSubtitleReceived', (data) => {
        setSubtitle(data.content);
      });

      // 语音识别事件
      CozeSocket.addListener('onAudioTranscriptUpdate', (data) => {
        setSubtitle(`您: ${data.content}`);
      });

      CozeSocket.addListener('onAudioTranscriptCompleted', (data) => {
        setSubtitle(`您: ${data.content}`);
      });

      // 错误事件
      CozeSocket.addListener('onError', (data) => {
        console.error('错误:', data.message);
        Alert.alert('错误', data.message);
      });
    };

    initializeSDK();
    setupListeners();

    // 组件卸载时清理
    return () => {
      CozeSocket.removeAllListeners();
      CozeSocket.release();
    };
  }, []);

  const handlePressIn = async () => {
    try {
      // 先取消当前会话
      await CozeSocket.cancelChat();
      
      // 清空字幕
      setSubtitle('');
      
      // 开始录音
      const success = await CozeSocket.startRecord();
      if (success) {
        setIsListening(true);
      } else {
        Alert.alert('错误', '开始录音失败');
      }
    } catch (error) {
      console.error('开始录音错误:', error);
      Alert.alert('错误', '开始录音失败: ' + error.message);
    }
  };

  const handlePressOut = async () => {
    if (isListening) {
      setIsListening(false);
      try {
        const success = await CozeSocket.endRecord();
        if (!success) {
          Alert.alert('错误', '结束录音失败');
        }
      } catch (error) {
        console.error('结束录音错误:', error);
        Alert.alert('错误', '结束录音失败: ' + error.message);
      }
    }
  };

  return (
    <View style={styles.container}>
      <Text style={styles.connectionStatus}>
        {isConnected ? '已连接' : '未连接'}
      </Text>
      
      <View style={styles.subtitleContainer}>
        <Text style={styles.subtitle}>{subtitle}</Text>
      </View>
      
      <TouchableOpacity
        style={[styles.recordButton, isListening && styles.recordingButton]}
        onPressIn={handlePressIn}
        onPressOut={handlePressOut}
      >
        <Text style={styles.buttonText}>
          {isListening ? '松开结束' : '按住说话'}
        </Text>
      </TouchableOpacity>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    padding: 20,
  },
  connectionStatus: {
    position: 'absolute',
    top: 20,
    right: 20,
    padding: 8,
    borderRadius: 4,
    backgroundColor: '#f0f0f0',
  },
  subtitleContainer: {
    flex: 1,
    width: '100%',
    justifyContent: 'center',
    alignItems: 'center',
    padding: 20,
  },
  subtitle: {
    fontSize: 18,
    textAlign: 'center',
    color: '#333',
  },
  recordButton: {
    width: 150,
    height: 150,
    borderRadius: 75,
    backgroundColor: '#4CAF50',
    justifyContent: 'center',
    alignItems: 'center',
    marginBottom: 30,
  },
  recordingButton: {
    backgroundColor: '#F44336',
  },
  buttonText: {
    color: 'white',
    fontSize: 18,
    fontWeight: 'bold',
  },
});

export default CozeVoiceChat;

API 参考

核心方法

| 方法 | 描述 | 参数 | 返回值 | |------|------|------|--------| | initialize() | 初始化 SDK | 无 | Promise | | startRecord() | 开始录音 | 无 | Promise | | endRecord() | 结束录音 | 无 | Promise | | cancelChat() | 取消当前会话 | 无 | Promise | | clearBuffers() | 清除音频缓冲区 | 无 | Promise | | release() | 释放 SDK 资源 | 无 | Promise | | checkRecordPermission() | 检查录音权限 | 无 | Promise |

事件监听方法

| 方法 | 描述 | 参数 | 返回值 | |------|------|------|--------| | addListener(eventType, listener) | 添加事件监听器 | eventType: 事件类型listener: 回调函数 | 订阅对象 | | removeListener(eventType, subscription) | 移除特定事件监听器 | eventType: 事件类型subscription: 订阅对象 | 无 | | removeAllListeners() | 移除所有事件监听器 | 无 | 无 |

事件类型

以下是所有可用的事件类型:

| 事件名称 | 描述 | 回调参数 | |---------|------|----------| | onWebSocketOpen | WebSocket 连接已打开 | { message: string } | | onWebSocketMessage | 收到 WebSocket 消息 | { data: string } | | onWebSocketError | WebSocket 错误 | { error: string } | | onWebSocketClosing | WebSocket 正在关闭 | { code: number, reason: string } | | onWebSocketClosed | WebSocket 已关闭 | { code: number, reason: string } | | onSubtitleReceived | 收到字幕 | { content: string, role: string } | | onAudioDataReceived | 收到音频数据 | { base64Audio: string } | | onAudioPlaybackCompleted | 音频播放完成 | { completed: boolean } | | onChatCreated | 会话创建成功 | { logId: string } | | onChatConfigUpdated | 会话配置更新成功 | { message: string } | | onChatInProgress | 会话正在进行中 | { chatId: string } | | onChatCompleted | 会话完成 | { chatId: string, usage: object } | | onChatFailed | 会话失败 | { chatId: string, errorCode: number, errorMsg: string } | | onChatCancelled | 会话已取消 | { cancelled: boolean } | | onMessageDelta | 增量消息 | { content: string, role: string, type: string } | | onMessageCompleted | 消息完成 | { messageId: string, content: string, type: string } | | onAudioCompleted | 音频回复完成 | { messageId: string } | | onAudioBufferCompleted | 音频缓冲区已提交 | { completed: boolean } | | onAudioBufferCleared | 音频缓冲区已清除 | { cleared: boolean } | | onConversationCleared | 会话已清除 | { cleared: boolean } | | onAudioTranscriptUpdate | 用户语音识别字幕更新 | { content: string } | | onAudioTranscriptCompleted | 用户语音识别完成 | { content: string } | | onRequiresAction | 需要客户端执行操作 | { chatId: string, toolCalls: array } | | onError | 错误事件 | { message: string } | | onRecordStart | 录音开始 | { success: boolean } | | onRecordEnd | 录音结束 | { success: boolean } | | onRecordCancel | 录音取消 | { success: boolean } | | onMessage | 通用消息 | 根据消息类型不同而变化 |

TypeScript 支持

该库现在完全支持 TypeScript,提供了完整的类型定义。您可以导入以下类型来增强您的开发体验:

import { EventType, CozeSocketManagerInterface } from 'react-native-coze-socket/types';

故障排除

常见问题

  1. 无法连接到服务器

    • 检查网络连接
    • 确保 SDK 初始化正确
  2. 录音权限问题

    • 确保在 AndroidManifest.xml 中声明了 RECORD_AUDIO 权限
    • 确保在运行时请求了录音权限
    • 使用 checkRecordPermission() 方法检查权限状态
  3. 音频播放问题

    • 检查设备音量
    • 确保音频格式配置正确
  4. 事件监听器不工作

    • 确保正确添加了事件监听器
    • 检查事件名称是否正确
    • 确保在组件卸载时移除了监听器
  5. TypeScript 类型错误

    • 确保您使用的是最新版本的库
    • 检查您的 TypeScript 版本是否兼容
    • 确保正确导入了类型定义

注意事项

  1. 该 SDK 目前仅支持 Android 平台
  2. 最低支持的 Android 版本为 Android 6.0 (API 23)
  3. 使用前必须获取录音权限
  4. 在组件卸载时应调用 release() 方法释放资源
  5. 在组件卸载时应移除所有事件监听器,以避免内存泄漏

版本历史

  • 1.0.6 - 当前版本

    • 添加完整的 TypeScript 支持
    • 扩展事件类型定义
    • 改进类型安全性
    • 修复已知问题
  • 1.0.5 - 上一版本

    • 初始发布版本
    • 支持基本的语音录制和播放功能
    • WebSocket 连接管理
    • 实时字幕显示