1
我一直在嘗試獲取MP3音頻流作爲浮點數組。我已經得到了下面的示例代碼的數組。我不確定我是否可以使用這個數組來應用FFT。因爲這個數組與我從C++的使用LAME的代碼中獲得的數組不匹配[或類似]。在java中獲取mp3音頻信號作爲數組
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.UnsupportedAudioFileException;
import javazoom.spi.mpeg.sampled.file.MpegAudioFileReader;
import org.tritonus.share.sampled.FloatSampleTools;
public class onjava {
public static void main(String[] args) {
try {
File file = new File("mymp3file.mp3");
MpegAudioFileReader mpegAudioFileReader = new MpegAudioFileReader();
int fl = mpegAudioFileReader.getAudioFileFormat(file).getFrameLength();
System.out.println(fl);
AudioInputStream in= AudioSystem.getAudioInputStream(file);
AudioInputStream din = null;
AudioFormat baseFormat = in.getFormat();
onjava oj = new onjava();
AudioFormat decodedFormat =
new AudioFormat(AudioFormat.Encoding.PCM_SIGNED,
baseFormat.getSampleRate(),
16,
baseFormat.getChannels(),
baseFormat.getChannels() * 2,
baseFormat.getSampleRate(),
false);
int len = (int)file.length();
din = AudioSystem.getAudioInputStream(decodedFormat, in);
oj.rawplay(decodedFormat, din, len, fl);
in.close();
} catch (IOException e) {
e.printStackTrace();
} catch (LineUnavailableException e) {
e.printStackTrace();
} catch (UnsupportedAudioFileException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void rawplay(AudioFormat targetFormat, AudioInputStream din , int len, int frameLength)
throws IOException, LineUnavailableException {
byte[] data = new byte[len-1];
float[] floatArray = new float[len-1];
SourceDataLine line = getLine(targetFormat);
File textFile = new File("outputfile.txt");
PrintStream printStream = new PrintStream(textFile);
System.setOut(printStream);
if (line != null) {
// Start
line.start();
int nBytesRead = 0, nBytesWritten = 0;
while (nBytesRead != -1) {
nBytesRead = din.read(data, 0, 8000);
if (nBytesRead != -1) {
//Please tell me if something is wrong with the arguments passed below
FloatSampleTools.byte2floatGeneric(data, 0, targetFormat.getFrameSize(), floatArray, 0, 1000, targetFormat);
for (int i = 0; i < nBytesRead; i++) {
if(floatArray[i] != 0.0)
System.out.println(floatArray[i]);
}
}
}
// Stop
line.drain();
line.stop();
line.close();
din.close();
}
}
private SourceDataLine getLine(AudioFormat audioFormat)
throws LineUnavailableException {
SourceDataLine res = null;
DataLine.Info info = new DataLine.Info(SourceDataLine.class,
audioFormat);
res = (SourceDataLine) AudioSystem.getLine(info);
res.open(audioFormat);
return res;
}
}
如果在上面的代碼中有任何錯誤,請提出建議。此外,如果任何其他純Java API可用於處理MP3文件。我需要mp3音頻流中的數組。
如果可以的話,還請告訴我有關LAME的純Java實現。
謝謝!
1)不要忘記提問。 2)*「這個數組與我從C++的代碼獲得的數據不匹配」* C++代碼在哪裏? –