我在Android项目中使用Chaquopy
。我的python类中有一个函数,该函数以PyObject
类型返回2D数组。现在,我想将其转换为java类中的2D数组。我该如何实现?
编辑:这是我的Python代码:
import numpy as np
from scipy.io import wavfile
def get_python_audio(file_path):
fs, data_test = wavfile.read(file_path)
print('data_test:', data_test.shape)
data = data_test[:, 0]
data = data[:, np.newaxis]
print('data:', data.shape)
return data
答案 0 :(得分:1)
在Java和Python之间转换数字数组的最快方法是使用字节数组。
我们假设wavfile.read
返回一维int16数组,但是该技术很容易适用于其他数据类型。然后在Python中,您可以执行以下操作:
def get_python_audio(file_path):
fs, data_test = wavfile.read(file_path)
return data_test.tobytes()
在Java中:
byte[] bytesData = yourModule.callAttr("get_python_audio", filePath).toJava(byte[].class);
short[] shortData = new short[bytesData.length / 2];
ByteBuffer.wrap(bytesData).order(ByteOrder.nativeOrder()).asShortBuffer().get(shortData);
如果音频具有多个通道,则必须分别转换每个通道。