简体   繁体   English

如何读取每个样本2字节大小的声卡输入流? (Java)

[英]How to read soundcard input stream at size of 2 bytes per sample? (Java)

I have this code: 我有以下代码:

final static AudioFormat format = new AudioFormat(48000, 16, 1, true, true);
TargetDataLine line;
    DataLine.Info info = new DataLine.Info(TargetDataLine.class, format);
    line=(TargetDataLine) AudioSystem.getLine(info);
    line.open(format);

    line.start();
    ByteArrayOutputStream out  = new ByteArrayOutputStream();
    int numBytesRead;
    byte[] data = new byte[16040];
    numBytesRead =  line.read(data, 0, data.length);

I want to to read 16-bit samples data but the function line.read() only allows me to use 8-bit data by variable byte - when I want to change it to int or short, it gives me an error. 我想读取16位样本数据,但函数line.read()仅允许我按可变字节使用8位数据-当我要将其更改为int或short时,它给我一个错误。 What can I do to get 16-bits data? 如何获取16位数据?

You can convert your bytes using ByteBuffer class: 您可以使用ByteBuffer类转换字节:

short[] shortArray = new shorts[data.lentgh / 2]; 
ByteBuffer            
   .wrap(data)
   .order(ByteOrder.LITTLE_ENDIAN)
   .asShortBuffer()
   .get(shortArray);

And yet another solution is to use DataInputStream which has a method .readShort() so you can read 16-bit data directly from your stream. 还有另一种解决方案是使用具有方法.readShort() DataInputStream ,以便您可以直接从流中读取16位数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM