Convert audio stream to WAV byte array in Java without temp file

Given an InputStream called in which contains audio data in a compressed format (such as MP3 or OGG), I wish to create a byte array containing a WAV conversion of the input data. Unfortunately, if you try to do this, JavaSound hands you the following error:

java.io.IOException: stream length not specified

I managed to get it to work by writing the wav to a temporary file, then reading it back in, as shown below:

AudioInputStream source = AudioSystem.getAudioInputStream(new BufferedInputStream(in, 1024));
AudioInputStream pcm = AudioSystem.getAudioInputStream(AudioFormat.Encoding.PCM_SIGNED, source);
AudioInputStream ulaw = AudioSystem.getAudioInputStream(AudioFormat.Encoding.ULAW, pcm);
File tempFile = File.createTempFile("wav", "tmp");
AudioSystem.write(ulaw, AudioFileFormat.Type.WAVE, tempFile);
// The fileToByteArray() method reads the file
// into a byte array; omitted for brevity
byte[] bytes = fileToByteArray(tempFile);
tempFile.delete();
return bytes;

This is obviously less desirable. Is there a better way?


Asked by: Daryl483 | Posted: 28-01-2022






Answer 1

The problem is that the most AudioFileWriters need to know the file size in advance if writing to an OutputStream. Because you can't provide this, it always fails. Unfortunatly, the default Java sound API implementation doesn't have any alternatives.

But you can try using the AudioOutputStream architecture from the Tritonus plugins (Tritonus is an open source implementation of the Java sound API): http://tritonus.org/plugins.html

Answered by: Carlos615 | Posted: 01-03-2022



Answer 2

I notice this one was asked very long time ago. In case any new person (using Java 7 and above) found this thread, note there is a better new way doing it via Files.readAllBytes API. See: How to convert .wav file into byte array?

Answered by: Grace516 | Posted: 01-03-2022



Answer 3

Too late, I know, but I was needed this, so this is my two cents on the topic.

public void UploadFiles(String fileName, byte[] bFile)
{
    String uploadedFileLocation = "c:\\";

    AudioInputStream source;
    AudioInputStream pcm;
    InputStream b_in = new ByteArrayInputStream(bFile);
    source = AudioSystem.getAudioInputStream(new BufferedInputStream(b_in));
    pcm = AudioSystem.getAudioInputStream(AudioFormat.Encoding.PCM_SIGNED, source);
    File newFile = new File(uploadedFileLocation + fileName);
    AudioSystem.write(pcm, Type.WAVE, newFile);

    source.close();
    pcm.close();
}

Answered by: Aida825 | Posted: 01-03-2022



Answer 4

The issue is easy to solve if you prepare class which will create correct header for you. In my example Example how to read audio input in wav buffer data goes in some buffer, after that I create header and have wav file in the buffer. No need in additional libraries. Just copy the code from my example.

Example how to use class which creates correct header in the buffer array:

public void run() {    
    try {    
        writer = new NewWaveWriter(44100);  

        byte[]buffer = new byte[256];  
        int res = 0;  
        while((res = m_audioInputStream.read(buffer)) > 0) {  
            writer.write(buffer, 0, res);  
        }  
    } catch (IOException e) {  
        System.out.println("Error: " + e.getMessage());  
    }    
}    

public byte[]getResult() throws IOException {  
    return writer.getByteBuffer();  
}  

And class NewWaveWriter you can find under my link.

Answered by: Daryl905 | Posted: 01-03-2022



Answer 5

This is very simple...

File f = new File(exportFileName+".tmp");
File f2 = new File(exportFileName);
long l = f.length();
FileInputStream fi = new FileInputStream(f);
AudioInputStream ai = new AudioInputStream(fi,mainFormat,l/4);
AudioSystem.write(ai, Type.WAVE, f2);
fi.close();
f.delete();

The .tmp file is a RAW audio file, the result is a WAV file with header.

Answered by: Blake738 | Posted: 01-03-2022



Similar questions

How do I convert an audio stream to MP3 using Java?

Is it possible using Java to convert a real time audio stream from the mixer to MP3? It has to be converted chunk by chunk otherwise the memory will be exhausted. I already know how to record but only to lossless formats such as wav and aiff. I need conversion as the audio comes in.


java - How to convert audio stream to .wav file and save

I am having some trouble figuring out how to convert audio data stream captured as 128 byte by a device to a .wav file and then how to save that .wav file. I am using eclipse with JRE8 to create a java project. Please let me know if any additional information would be helpful. Here is the code I have thus far: public void StartStreaming(){ {if(device !=null)} {device.startAudioInput();}} public ...


java - Convert an audio stream to PCM

I'm trying to get an audio stream from a text-to-speech interface (MaryTTS) and stream it in an SIP RTP session (using Peers). Peers wants a SoundSource to stream audio, which is an interface defined as public interface SoundSource { byte[] readData(); } and MaryTTS synthesises a String to an AudioInputStream. I tried to simply read the ...


How do I convert an audio stream to MP3 using Java?

Is it possible using Java to convert a real time audio stream from the mixer to MP3? It has to be converted chunk by chunk otherwise the memory will be exhausted. I already know how to record but only to lossless formats such as wav and aiff. I need conversion as the audio comes in.


java - How to convert a zip file into an octet stream

I am working on SOAP web services. I have been given a third party WSDL URL for which I need to generate client code. I need to pass a zip file which contains a bundle of XML, for which the passing parameter should be type octet stream. I don't know how to pass an argument as an octet stream. How can I do this?


java - How can I convert a Stream into an Int?

I need to write numbers in a text file, then I have to read the file, and finally sume the numbers. I can write and read the file, but I don´t know how to make the math opperation. package clase.pkg13.de.septiembre; import java.io.*; public class FicheroTexto { public static void main (String args[]) { try { PrintWriter salida = new PrintWriter ( new BufferedWriter(new FileWriter...


How to convert a Java 8 Stream to an Array?

What is the easiest/shortest way to convert a Java 8 Stream into an array?


java - How to convert audio stream to .wav file and save

I am having some trouble figuring out how to convert audio data stream captured as 128 byte by a device to a .wav file and then how to save that .wav file. I am using eclipse with JRE8 to create a java project. Please let me know if any additional information would be helpful. Here is the code I have thus far: public void StartStreaming(){ {if(device !=null)} {device.startAudioInput();}} public ...


java - Java8: convert one map to another map using stream

I need to convert a Java HashMap to an instance of TreeMap (including map contents) HashMap<String, Object> src = ...; TreeMap<String, Object> dest = src.entrySet().stream() .filter( ... ) .collect(Collectors.toMap( ???, ???, ???, TreeMap::new)); What should I put in place of ??? to make this code compilable?


C# and Java how to convert bytes for stream

I made few attempts at sending data from C# UDP server to Java client with no luck. I know that there is difference between bytes in Java and C# however do not fully understand how to implement it. Any help would be great. Below is my C# code: TimeSpan t = DateTime.UtcNow - new DateTime(1970, 1, 1); int secondsSinceEpoch = (int)t.TotalSeconds; { byte[] data = new byte[1024]; IPAddress UDP_...


Java - How to convert Scala Stream to Java Stream?

I have a Java application that receives a Scala Stream. I need to convert this to a Java Stream. How can I do this in Java?


Java 8 : Convert dates using stream

I'm trying to convert dates dynamically. I tried this method but it is returning void. How to make it an array of LocalDate objects? String[] datesStrings = {"2015-03-04", "2014-02-01", "2012-03-15"}; LocalDate[] dates = Stream.of(datesStrings) .forEach(a -> LocalDate.parse(a)); // This returns void so I ...


convert byte stream to string from socket in server side java

I serialized an object to bytes and send to the server side. in the server side i got the byte stream but i want to print the object/string i got from the server in order to verify i got it well server side: CarServerSocket = new ServerSocket(4441); System.out.println("Server is ready and waiting for connection from client..\n"); try { while (true) { carSocket = CarSe...


How to convert TIS-620 string to UTF-8 string in Java?


java - Convert to date

I'm trying to create number of Evenement instances and set the date for them: for (int i=2004; i<2009; i++){ evenementen.add(new Evenement("Rock Werchter", "Rock", "Werchter", 200000, (Date)formatter.parse(i+"/07/03"))); But I can't seem to get it to work, Any ideas?


java - Convert PNG to bitonal TIFF

-Edit- FYI.. I am converting b&w documents scanned in as greyscale or color. 1)The first solution worked, it just reversed black & white (black background, white text). It also took nearly 10 minutes. 2)The JAI solution in the 2nd answer didn't work for me. I tried it before posting here. Has anyone worked with other libraries free or pay that handle image manipulation well? -Original...


java - How to convert a double to long without casting?

What is the best way to convert a double to a long without casting? For example: double d = 394.000; long l = (new Double(d)).longValue(); System.out.println("double=" + d + ", long=" + l);


Convert String from ASCII to EBCDIC in Java?

I need to write a 'simple' util to convert from ASCII to EBCDIC? The Ascii is coming from Java, Web and going to an AS400. I've had a google around, can't seem to find a easy solution (maybe coz there isn't one :( ). I was hoping for an opensource util or paid for util that has already been written. Like this maybe? Converter.convertToAscii(String textFromAS400) Converter.convertToEBCD...


How do I convert an audio stream to MP3 using Java?

Is it possible using Java to convert a real time audio stream from the mixer to MP3? It has to be converted chunk by chunk otherwise the memory will be exhausted. I already know how to record but only to lossless formats such as wav and aiff. I need conversion as the audio comes in.


Need to convert EPS files to jpg/png in Java

We have a webapp where people can upload various image file types and on the backend we convert them to a standard type (typically png or jpeg). Right now we are using ImageIO to do this. However the new requirement is to be able to support eps files. I haven't found any libraries that support EPS in ImageIO, or much in the way of support for reading eps files in java. Any suggestions for reading eps files and c...


java - Convert JSON to Map

What is the best way to convert a JSON code as this: { "data" : { "field1" : "value1", "field2" : "value2" } } in a Java Map in which one the keys are (field1, field2) and the values for those fields are (value1, value2). Any ideas? Should I use Json-lib for that? Or better if I write my own parser?


is there a simple way to convert my XML object back to String in java?

I have an xml document object that I need to convert into a string. Is there as simple way to do this?


java - how to convert hex to byte for the following program?

public static String asHex (byte buf[]) { StringBuffer strbuf = new StringBuffer(buf.length * 2); int i; for (i = 0; i < buf.length; i++) { if (((int) buf[i] & 0xff) < 0x10) strbuf.append("0"); strbuf.append(Long.toString((int) buf[i] & 0xff, 16)); } return strbuf.toString(); }






Still can't find your answer? Check out these amazing Java communities for help...



Java Reddit Community | Java Help Reddit Community | Dev.to Java Community | Java Discord | Java Programmers (Facebook) | Java developers (Facebook)



top