[英]How to convert a byte array into an AudioInputStream in Java
我想將字節數組轉換為AudioInputStream。 字節數組之前是從* .wav文件填充的。 我有以下代碼:
public static AudioInputStream writeBytesBackToStream(byte[] bytes) {
ByteArrayInputStream baiut = new ByteArrayInputStream(bytes);
AudioInputStream stream = null;
try {
stream = AudioSystem.getAudioInputStream(baiut);
} catch (UnsupportedAudioFileException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if(stream.equals(null) || stream == null) {
System.out.println("WARNING: Stream read by byte array is null!");
}
return stream;
}
現在,我只想將此字節數組轉換為AudioInputStream,但是會引發UnsupportedAudioFileException:
javax.sound.sampled.UnsupportedAudioFileException: could not get audio input stream from input stream
有人知道嗎?
如果數據實際上是PCM,則另一種方法是手動設置AudioFormat參數。 這是創建A小調的示例。
byte[] b = new byte[64000];
//lets make a 440hz tone for 1s at 32kbps, and 523.25hz.
for(int i = 0; i<b.length/2; i++){
b[i*2+1] = (byte)(127*Math.sin(4*Math.PI*440.0/b.length*i));
b[i*2] = (byte)(127*Math.sin(4*Math.PI*523.25/b.length*i));
}
AudioInputStream stream = new AudioInputStream(
new ByteArrayInputStream(b),
new AudioFormat(16000, 8, 2, true, false),
64000
);
如果要使字節變成聲音並且有耳機,請當心。
如果您正確讀取WAV文件,則字節數組將僅包含原始PCM數據。 因此,AudioSystem無法識別流的格式並引發異常。
這不能設計使然。 您需要在流中提供完整的音頻格式圖像,以使AudioSystem識別流是什么格式,而不僅僅是原始數據。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.