This commit is contained in:
wangjiyu 2025-04-10 10:37:11 +08:00
parent d556d8f294
commit f1414abe5c
1 changed files with 36 additions and 18 deletions

View File

@ -3,6 +3,7 @@
#define PY_ARRAY_UNIQUE_SYMBOL rtc_plugins_ARRAY_API #define PY_ARRAY_UNIQUE_SYMBOL rtc_plugins_ARRAY_API
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
#include <numpy/ndarrayobject.h> #include <numpy/ndarrayobject.h>
#include <numpy/arrayobject.h>
#include <stdio.h> #include <stdio.h>
@ -34,23 +35,7 @@ int initSend(const char* destRoomId, const int16_t destChannelIndex) {
return -1; 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() { py::object create_int16_array() {
// 1. 定义数组维度1维长度为 4 // 1. 定义数组维度1维长度为 4
npy_intp dims[1] = {4}; npy_intp dims[1] = {4};
@ -73,10 +58,42 @@ py::object create_int16_array() {
// 4. 转换为 py::object自动管理引用计数 // 4. 转换为 py::object自动管理引用计数
return py::object(py::handle<>(py_array)); 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<PyArrayObject*>(arr.ptr());
// 检查数据长度
if (PyArray_SIZE(npArray) != static_cast<npy_intp>(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) { uint64_t dataLen) {
try { try {
py::object pyData = create_int16_array(); //py::object pyData = create_int16_array();
std::cout << "step 1" << std::endl; std::cout << "step 1" << std::endl;
// 1. 检查输入有效性 // 1. 检查输入有效性
if (pyData.ptr() == nullptr) { if (pyData.ptr() == nullptr) {
@ -125,6 +142,7 @@ int sendCustomAudioData(const int16_t destChannelIndex, py::object pD, int32_t s
return -1; return -1;
} }
} }
*/
void init_numpy() { void init_numpy() {