diff --git a/rtc_plugins.cpp b/rtc_plugins.cpp index c03a58c..1bf2007 100644 --- a/rtc_plugins.cpp +++ b/rtc_plugins.cpp @@ -3,6 +3,7 @@ #define PY_ARRAY_UNIQUE_SYMBOL rtc_plugins_ARRAY_API #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION #include +#include #include @@ -34,23 +35,7 @@ int initSend(const char* destRoomId, const int16_t destChannelIndex) { return -1; } } -py::object create_numpy_array() { - // 确保已调用 import_array() - if (PyArray_API == nullptr) { - throw std::runtime_error("NumPy API not initialized"); - } - // 创建数组 - npy_intp dims[1] = {4}; - int32_t data[4] = {1, 2, 3, 4}; - - PyObject* py_array = PyArray_SimpleNewFromData(1, dims, NPY_INT32, data); - if (!py_array) { - throw std::runtime_error("Failed to create NumPy array"); - } - - return py::object(py::handle<>(py_array)); -} py::object create_int16_array() { // 1. 定义数组维度(1维,长度为 4) npy_intp dims[1] = {4}; @@ -73,10 +58,42 @@ py::object create_int16_array() { // 4. 转换为 py::object(自动管理引用计数) return py::object(py::handle<>(py_array)); } -int sendCustomAudioData(const int16_t destChannelIndex, py::object pD, int32_t sampleRate, uint64_t channelNum, +int sendCustomAudioData(int16_t destChannelIndex, py::object pD, + int32_t sampleRate, uint64_t channelNum, uint64_t dataLen) { + try { + // 强制转换为 int16 连续数组 + PyObject* py_array = PyArray_FROM_OTF( + pD.ptr(), + NPY_INT16, + NPY_ARRAY_IN_ARRAY | NPY_ARRAY_FORCECAST + ); + if (!py_array) { + throw std::runtime_error("Failed to convert input to int16 array"); + } + + py::object arr = py::handle<>(py_array); + PyArrayObject* npArray = reinterpret_cast(arr.ptr()); + + // 检查数据长度 + if (PyArray_SIZE(npArray) != static_cast(dataLen)) { + throw std::runtime_error("Array length does not match dataLen"); + } + + // 处理数据... + void* dataPtr = PyArray_DATA(npArray); + return RTCContext::instance().sendCustomAudioData( + destChannelIndex, dataPtr, sampleRate, channelNum, dataLen + ); + } catch (...) { + PyErr_SetString(PyExc_RuntimeError, "Invalid audio data"); + return -1; + } +} +/* +int sendCustomAudioData(const int16_t destChannelIndex, py::object pyData, int32_t sampleRate, uint64_t channelNum, uint64_t dataLen) { try { - py::object pyData = create_int16_array(); + //py::object pyData = create_int16_array(); std::cout << "step 1" << std::endl; // 1. 检查输入有效性 if (pyData.ptr() == nullptr) { @@ -125,6 +142,7 @@ int sendCustomAudioData(const int16_t destChannelIndex, py::object pD, int32_t s return -1; } } + */ void init_numpy() {