[Python] how to convert a python np.ndarray to Java Float[] array [duplicate]

Discussão em 'Python' iniciado por Stack, Março 8, 2025.

  1. Stack

    Stack Membro Participativo

    I am using py4j for a project to connect my Python code to a JVM. Now this project requires me to pass an audio signal from the Python end to the Java end. I am using Librosa to create the audio signal array from the audio file. This gives me a float64 numpy array. Now I want to pass this audio signal array as a parameter of a Java function using Py4J. Now this seems to be the problematic part due to difference in data types I assume.

    I tried to pass it after converting it to a byte array, but although the dimension of the array remains the same the values somehow all changed making the results of my projects very inaccurate.

    Python side:

    audio, sr = librosa.load(r"Audio/snoring.wav", sr=16000)
    byte_array = audio.tobytes()
    mel2 = gateway.entry_point.checkSignal()


    Java side:

    public void checkSignal(byte[] byteArray){
    FloatBuffer floatBuffer = ByteBuffer.wrap(byteArray).asFloatBuffer();
    float[] floatArray = new float[floatBuffer.remaining()];
    floatBuffer.get(floatArray);

    if(floatArray.length>0){
    System.out.println("the signal has been received." + floatArray.length);
    }

    signal = floatArray;
    }


    Before that I had my audio file stored in the Java project directory and I would pass the audio file name from the Python side to the Java function, and as expected it worked flawlessly. But the need to pass the signal as a parameter is making this quite hard.

    Continue reading...

Compartilhe esta Página