Michael
Michael

Reputation: 2773

How to Read MP3

Using this post I was able to find out how to read mp3 files, but I'm still confused as to how to actually use this.

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);

After these declarations, how do you use din? I know the loop would look something like this:

while (/*What do I put here??*/){
    int currentByte = din.read();
}

In other words, I'm just asking how to read the entire array of bytes from the mp3 file, inspecting them one at a time in a loop.

Upvotes: 2

Views: 3927

Answers (2)

ivan
ivan

Reputation: 1205

try this code: import java.io.DataInputStream; import java.io.FileInputStream;

public class Main {

  public static void main(String[] args) throws Exception {
    FileInputStream fin = new FileInputStream("C:/Array.txt");
    DataInputStream din = new DataInputStream(fin);

    byte b[] = new byte[10];
    din.read(b);
    din.close();
  }

provided by:http://www.java2s.com/Tutorial/Java/0180__File/ReadbytearrayfromfileusingDataInputStream.htm

Upvotes: 0

Maximillian Laumeister
Maximillian Laumeister

Reputation: 20389

AudioInputStream.read() returns -1 when it's out of data, so you can break your loop when that happens:

while (true){
    int currentByte = din.read();
    if (currentByte == -1) break;
    // Handling code
}

Upvotes: 1

Related Questions