3

I am modifying an application that plays audio data to write the data to a file instead. As it is currently implemented, a byte array is filled dynamically, and the contents of this buffer are written to a SourceDataLine each time it is filled. I basically want to write that buffer out to a file in a specified format.

I have read through this official tutorial and came across this code snipped for writing audio data to a file:

File fileOut = new File(someNewPathName);
AudioFileFormat.Type fileType = fileFormat.getType();
if (AudioSystem.isFileTypeSupported(fileType, 
    audioInputStream)) {
  AudioSystem.write(audioInputStream, fileType, fileOut);
}

I see from the API documentation that I can construct an AudioInputStream using a TargetDataLine, however in my case I have a SourceDataLine. I don't know how to get the data from my byte array into the TargetDataLine since it implements the read() method instead of write(). Other uses of the AudioInputStream in that and other documentation treat it as a way of reading from a file, so I'm a little confused by its use with AudioSystem.write().

So, how can I get the data from a SourceDataLine, or from the buffer directly, into a TargetDataLine or AudioInputStream so that it can be written out to a file?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Travis Christian
  • 2,412
  • 2
  • 24
  • 41
  • 1
    what is the solution you used ? Were you able to write in a file what's being played/listened onto the speakers ? – coding_idiot Oct 02 '13 at 08:19
  • @coding_idiot the audio was just a sequence of tones, so I was able to reproduce them from a tone generator more easily than copying them programmatically – Travis Christian Oct 07 '13 at 04:02

1 Answers1

2
  1. Use the byte[] to establish a ByteArrayInputStream
  2. Provide the BAIS to AudioSystem.getAudioInputStream(InputStream)
  3. Use the AIS in AudioSystem.write(..)
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • After replacing the call to SourceDataLine.write() with this, I'm getting an UnsupportedAudioFileException on step 3: "could not get audio input stream from input stream". Why would the data be valid for writing to a SourceDataLine but not for creating an AudioInputStream? – Travis Christian Mar 05 '12 at 22:45
  • SSCCE wasn't really feasible in this case. I moved on to a different solution, but this is the answer to the problem I was initially facing so I'm accepting it. – Travis Christian Apr 05 '12 at 15:26