Java 如何从 MP3 中获取音频数据?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/938304/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get audio data from a MP3?
提问by dedalo
I'm working on an application that has to process audio files. When using mp3 files I'm not sure how to handle data (the data I'm interested in are the the audio bytes, the ones that represent what we hear).
我正在开发一个必须处理音频文件的应用程序。使用 mp3 文件时,我不确定如何处理数据(我感兴趣的数据是音频字节,代表我们听到的内容)。
If I'm using a wav file I know I have a 44 bytes header and then the data. When it comes to an mp3, I've read that they are composed by frames, each frame containing a header and audio data. Is it possible to get all the audio data from a mp3 file?
如果我使用的是 wav 文件,我知道我有一个 44 字节的标题,然后是数据。当谈到 mp3 时,我读到它们是由帧组成的,每个帧都包含一个标题和音频数据。是否可以从 mp3 文件中获取所有音频数据?
I'm using java (I've added MP3SPI, Jlayer, and Tritonus) and I'm able to get the bytes from the file, but I'm not sure about what these bytes represent or how to handle then.
我正在使用 java(我添加了 MP3SPI、Jlayer 和 Tritonus)并且我能够从文件中获取字节,但我不确定这些字节代表什么或如何处理。
采纳答案by Jon Skeet
From the documentation for MP3SPI:
File file = new File(filename);
AudioInputStream in= AudioSystem.getAudioInputStream(file);
AudioInputStream din = null;
AudioFormat baseFormat = in.getFormat();
AudioFormat decodedFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED,
baseFormat.getSampleRate(),
16,
baseFormat.getChannels(),
baseFormat.getChannels() * 2,
baseFormat.getSampleRate(),
false);
din = AudioSystem.getAudioInputStream(decodedFormat, in);
You then just read data from din
- it will be the "raw" data as per decodedFormat
. (See the docs for AudioFormat
for more information.)
然后您只需从中读取数据din
- 它将是“原始”数据decodedFormat
。(有关更多信息,请参阅文档AudioFormat
。)
(Note that this sample code doesn't close the stream or anything like that - use appropriate try/finally blocks as normal.)
(请注意,此示例代码不会关闭流或类似的东西 - 正常使用适当的 try/finally 块。)
回答by sybreon
The data that you want are the actual samples, while MP3 represents the data differently. So, like what everyone else has said - you need a library to decode the MP3 data into actual samples for your purpose.
您想要的数据是实际样本,而 MP3 以不同方式表示数据。因此,就像其他人所说的那样 - 您需要一个库来将 MP3 数据解码为实际样本,以达到您的目的。