javaaudiowavamazon-pollyaudioinputstream

Save ogg stream provided by AWS Polly into a wav file


I am trying to create a webpage, where user will be able to listen to the text he types. I also want to provide a functionality to download the media in .wav format.

I am able to get AudioStream from AmazonPollyClient but not able to save the stream to .wav file.

Here is what I am trying...

public void convertToWav(SynthesizeSpeechResult result, File convertedFile) throws IOException {

    try (AudioInputStream sias = AudioSystem.getAudioInputStream(result.getAudioStream())){

        AudioFormat newFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, 8000f, 16, 1, 2, 8000f, false);
        AudioInputStream convert1AIS = AudioSystem.getAudioInputStream(newFormat, sias);

        AudioSystem.write(convert1AIS, AudioFileFormat.Type.WAVE, convertedFile);

        convert1AIS.close();
    } catch (UnsupportedAudioFileException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    System.gc();
}

but everytime I call getAudioInputStream() it throws IOException

java.io.IOException: mark/reset not supported
    at java.io.InputStream.reset(InputStream.java:348)
    at com.amazonaws.internal.SdkFilterInputStream.reset(SdkFilterInputStream.java:112)
    at com.amazonaws.event.ProgressInputStream.reset(ProgressInputStream.java:168)
    at com.sun.media.sound.SoftMidiAudioFileReader.getAudioInputStream(SoftMidiAudioFileReader.java:139)
    at javax.sound.sampled.AudioSystem.getAudioInputStream(AudioSystem.java:1113)

P.S: I have tried wrapping result.getAudioStream() in BufferedInputStream(). No show!

Any help will be appreciated.


Solution

  • Finally, I have figured out way to save InputStream provided by polly-aws-sdk

    public static boolean getWavFile(String filePath, InputStream audioStream) throws IOException {
    
        boolean result = false;
        try {
    
            byte[] decodedData = IOUtils.toByteArray(audioStream);
    
            System.out.println(">>Decoded Data" + Arrays.toString(decodedData));
            File outFile = new File(filePath);
            AudioFormat format = new AudioFormat(8000, 16, 1, true, false);
            AudioSystem.write(new AudioInputStream(new ByteArrayInputStream(
                    decodedData), format, decodedData.length), AudioFileFormat.Type.WAVE, outFile);
            result = true;
            return result;
        } catch (IOException ex) {
            System.out.println("<<getWavFile - impl" + ex);
            return result;
    
        }
    }