在Java中将byte[]转换为short[]

6

可能是重复问题:
在Java中将字节数组转换为短整型数组并再次转换回来

Xuggler中的encodeAudio()方法具有以下参数:

  • int streamIndes
  • short[] samples
  • long timeStamp
  • TimeUnit unit

  • 使用javax.sound.sampled中的TargetDataLine,我可以将数据读入一个byte[]数组。

    byte[] tempBuffer = new byte[10000];
    fromMic.read(tempBuffer,0,tempBuffer.length);
    

    但问题在于samples参数需要short[]类型。


    5
    将字节数组转换为短整型数组,再将其转换回来的Java代码如下: public static byte[] toByteArray(short[] data) { byte[] bytes = new byte[data.length * 2]; for (int i = 0; i < data.length; i++) { bytes[i * 2] = (byte) (data[i] >> 8); bytes[(i * 2) + 1] = (byte) data[i]; } return bytes; } public static short[] toShortArray(byte[] data) { short[] shorts = new short[data.length / 2]; for (int i = 0; i < shorts.length; i++) { shorts[i] = (short) ((data[i * 2] << 8) | (data[(i * 2) + 1] & 0xff)); } return shorts; } - Rohit Jain
    我没有使用BigEndian编码。 - An SO User
    这并不像看起来那么简单。你有一个特定格式的字节数组,并且需要进行一些转换。请参阅:https://groups.google.com/forum/?fromgroups=#!topic/xuggler-users/cKLS5KmbEIM - Diego Basch
    1个回答

    10

    你很幸运,因为byte可以被完全转换为short,所以:

    // Grab size of the byte array, create an array of shorts of the same size
    int size = byteArray.length;
    short[] shortArray = new short[size];
    
    for (int index = 0; index < size; index++)
        shortArray[index] = (short) byteArray[index];
    

    然后使用shortArray

    注意:就原始类型而言,Java总是按照大端序处理它们,因此转换比如说字节ff会得到短整型00ff


    2
    哎呀...是的,如果是这种情况,第一个评论就是你的解决方案。 - fge
    1
    笔误... i++ 应该改为 index++。 - phatfingers
    @phatfingers:你的名字已经说明了一切,不是吗 ;) 已修复,谢谢! - fge
    1
    @LittleChild 当然可以,因为如果有任何问题,整个StackOverflow都可以找到它的问题所在。 - fge
    @fge 抱歉,但我很笨。 - An SO User
    显示剩余4条评论

    网页内容由stack overflow 提供, 点击上面的
    可以查看英文原文,
    原文链接