문제

I need to get the values from the AudioInputStream and store it in a byte[]. Calling a read(byte[]) returns -1. If I'm able to read the values as integers, I can convert it to byte[]. How do I get around either of the problems ?

도움이 되었습니까?

해결책

If the intention is to store the sound data in a byte[], the best approach is not to get an AudioInputStream at all. Instead, just use a plain InputStream.

The AudioInputStream typically strips the first bytes from an input stream (because they contain formatting data) and then only provides the frames or samples of that stream. Doing it using an InputStream on the other hand, you should be able to get all the bytes. Then once the entire data is in a byte array, an AudioInputStream can be formed from the byte array (if needed).

다른 팁

UPDATED

Use apache commons IOUtils to read the bytes from the wav file.

        InputStream is = -> your FileInputStream
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        IOUtils.copy(is, os);
        os.flush();
        os.close();

        byte[] ba = os.toByteArray();

You cannot read it directly to a ByteArrayOutputStream or you´re gonna get

java.io.IOException: stream length not specified
at com.sun.media.sound.WaveFileWriter.write(Unknown Source)
at javax.sound.sampled.AudioSystem.write(Unknown Source)

It is hard to understand what exactly you want: byte array with data or byte array with WAV file inside. Byte array with only sound data is a very simple task: copy from AudioInputStream to ByteArrayOutputStream.

The second case is more complex. In this case you should read from AudioInputStream to ByteArrayOutputStream and then form WAVE header. I can provide you two examples. I hope they will help you.

How to record audio to byte array - it is example of recording audio to byte array with wave file inside.

How to detect sound - it shows how AudioInputStream can be processed.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top