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

时间:2012-12-25 18:55:33

标签: java

  

可能重复:
  byte array to short array and back again in java

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

  • int streamIndes
  • 短[]样本
  • long timeStamp
  • TimeUnit unit

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

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

    但问题是samples参数需要short[]

    1 个答案:

    答案 0 :(得分:9)

    你很幸运byteshort是“完全可投递”的,所以:

    // 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