简体   繁体   中英

How to code to play MP3?

I was making a few lines of code which alternatively prints out "tick"s and "tock"s every 0.5 second, and prints out "done!" after 60 seconds.

import javax.sound.sampled.*;

public class Thread0001 {
    public static void main(String args[]) {
        for(int i=0; i<60; i++) {
            try {
                Thread.sleep(500);
                if(i%2 == 0) {
                    System.out.print("tick ");
                    try {
                        AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(Thread0001.class.getClass().getResource
                                ("Users/Marshall/Documents/Sources/Elevator.mp3"));
                        Clip clip = AudioSystem.getClip();
                        clip.open(audioInputStream);
                        clip.start();
                    } catch(Exception e) {

                    }
                }
                else
                    System.out.print("tock ");
                if(i == 59) { // when it reaches 60 seconds
                    System.out.println("done!");
                }
            } catch(Exception e) {

            }
        }
    }
}

Well, everything seemed fine but one thing - I also put a code to emit an elevator bell sound every "tick". This code does not seem to be working, so can somebody help me out with this issue?

You will need to load a library, such as the one provided by JavaZoom, in order to play an mp3. If you are already using JavaFX for graphic components, you might consider using it for playback, as it's audio now supports mp3.

After that, the next most likely error to arise would be either "file not found" or "invalid format". The former would most likely be due to trickiness in getting the relative address correct. The latter would most likely be due to the encoded wav file being recorded at a precision greater than 44100 fps or 16 bit encoding. However you won't know which might be occurring unless you follow the suggestion to add e.printStackTrace();.

The code as you have written should be fairly approximate, to within maybe a dozen or so milliseconds at worst. To improve the code, you could preload the Clip outside of the loop and just reposition to the starting frame and call play. Another option would be to play via SourceDataLine instead, which starts very quickly. As it stands, every iteration you are loading the file into RAM and then (only after THAT is completed) playing the file from RAM.

Frame accuracy (within 1/44100 sec) is possible, but the method I know requires the use of SourceDataLine and the counting of elapsed frames over a continuous playback. Probably overkill.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM