Воспроизведение аудиофайла в формате OggOpus в JAVA
Работаю с API Yandex SpeechKit. При запросе данных через API возвращается бинарное содержимое аудиофайла. Это "содержимое" я пытался сохранить в формат .ogg и затем воспроизвести в Java. Пробовал обычные методы Java и множество библиотек все безуспешно. Затем попытался сохранять файл в формате .opus и конвертировать его.
Для конвертации использовал библиотеки Jorbis, EasyOgg, Vorbisspi, LibJitsi, Jogg. Для воспроизведения использовал библиотеки TinySound, а также "самописные" варианты. Как итог, ничего не работает.
Для представления с чем работаю вот ссылка на документацию Yandex.
Фрагмент кода с сохранением файла.
private void getSynthesizeVoiceInFile(String filePath, HttpURLConnection http){
File file = null;
try {
int count = 1, c;
file = new File(filePath + ".opus");
while (file.exists()){
file = new File(filePath + "_" + count + ".opus");
count++;
}
InputStream is = http.getInputStream();
FileOutputStream fos = new FileOutputStream(file);
while ((c = is.read()) != -1) fos.write(c);
fos.close();
is.close();
log.DEBUG("GetSynthesizeVoice.getSynthesizeVoiceInFile: Create file. Filepath: " + file.getPath());
}catch (IOException | NullPointerException e){
log.ERROR("GetSynthesizeVoice.getSynthesizeVoiceInFile: Failed to write or create file. Filepath: " + file.getPath());
e.printStackTrace();
}
}
Надеюсь знающие люди подскажут. Я уже просто не знаю в какую сторону копать...
Ответы (1 шт):
Нашел решение проблемы, думаю некоторым будет это полезно. А решение простое. На этапе формирования http запроса дополнительным параметром передал строку с кодировкой
&format=lpcm&sampleRateHertz=48000
После этого изменил сохранение файла в формат .raw
Соответственно функция сохранения приобрела следующий вид:
private void getSynthesizeVoiceInFile(String filePath, HttpURLConnection http){
File file = null;
AudioInputStream din = null;
try {
int count = 1, c;
file = new File(filePath + ".raw");
while (file.exists()){
file = new File(filePath + "_" + count + ".raw");
count++;
}
InputStream is = http.getInputStream();
FileOutputStream fos = new FileOutputStream(file);
while ((c = is.read()) != -1) fos.write(c);
fos.close();
new testPlay().play(new FileInputStream(file));
is.close();
log.DEBUG("GetSynthesizeVoice.getSynthesizeVoiceInFile: Create file. Filepath: " + file.getPath());
}catch (IOException | NullPointerException e){
log.ERROR("GetSynthesizeVoice.getSynthesizeVoiceInFile: Failed to write or create file. Filepath: " + file.getPath());
e.printStackTrace();
}
}
Поскольку на выходе получается аудиофайл с кодировкой LPCM, то его получается "проиграть" без особых танцев с бубном и дополнительных библиотек.
Класс который вызывается в коде new testPlay().play(new FileInputStream(file));, полностью представлен ниже:
import javax.sound.sampled.*;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
public class testPlay {
public void play(InputStream rawfile) {
byte buf[] = new byte[1024];
int len;
try {
BufferedInputStream raw = new BufferedInputStream(rawfile);
AudioFormat format = new AudioFormat(
48000,
16,
1,
true,
false
);
DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);
SourceDataLine line = (SourceDataLine) AudioSystem.getLine(info);
line.open(format, 1024);
line.start();
while ((len = raw.read(buf)) != -1)
line.write(buf, 0, len);
line.drain();
line.stop();
line.close();
}catch (LineUnavailableException | IOException e){
e.printStackTrace();
}
}
}