简体   繁体   中英

Java audio... getting from byte[] of raw waveform to playable Clip

I'm trying to figure out how to play a raw 8-bit (signed) waveform using Java, and struggling because it seems like every API example I find assumes media playback from a file. Here's what I have so far (shortened for clarity):

// Assume waveform array has 480 bytes, and consists of 24 periods of a 1000hz sine wave.
byte[] waveform = WaveformGenerator.generateWaveform();

Clip clip = AudioSystem.getClip();
ByteArrayInputStream fakeInputStream= new ByteArrayInputStream(waveform);
AudioInputStream inputStream = AudioSystem.getAudioInputStream(fakeInputStream);
clip.open(inputStream);
clip.start();

When it runs, AudioSystem.getAudioInputStream(fakeInputStream) throws javax.sound.sampled.UnsupportedAudioFileException: Stream of unsupported format before it even makes it to clip.open(inputStream);

ok, fair enough... I guess I need to tell it that it's a mono 8-bit PCM waveform. So, I created an AudioFormat to let it know that it's 48khz 8-bit PCM...

AudioFormat audioFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, 48000, 8, 1, 1, 48000, false);

... then realized (too late) that the variant of AudioSystem.getAudioInputStream() that allows you to specify the format requires that you already have an AudioInputStream. As far as I can tell, there's no variant of getAudioInputStream that allows you to SIMULTANEOUSLY specify its type and content.

Obviously, I'm going down the wrong track here. So... what is the correct way to get from a byte array containing a raw 8-bit signed PCM waveform to an audio object that can be play()'ed?

Call the constructor directly like this:

AudioInputStream inputStream = new AudioInputStream(fakeInputStream, audioFormat, waveform.length);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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