BackgroundMP3.java


Below is the syntax highlighted version of BackgroundMP3.java from §1.5 Input and Output.


/******************************************************************************
 *  Compilation:  javac -classpath .:jl1.0.jar BackgroundMP3.java         (OS X)
 *                javac -classpath .;jl1.0.jar BackgroundMP3.java         (Windows)
 *  Execution:    java -classpath .:jl1.0.jar BackgroundMP3 filename.mp3  (OS X / Linux)
 *                java -classpath .;jl1.0.jar BackgroundMP3 filename.mp3  (Windows)
 *
 *  Plays an MP3 file using the JLayer MP3 library.
 *
 *  Reference:  http://www.javazoom.net/javalayer/sources.html
 *
 *
 *  To execute, get the file jl1.0.jar from the website above or from
 *
 *      https://introcs.cs.princeton.edu/java/24inout/jl1.0.jar
 *
 *  and put it in your working directory with this file BackgroundMP3.java.
 *
 ******************************************************************************/

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;

import javazoom.jl.player.advanced.AdvancedPlayer;

public class BackgroundMP3 {

    public static void play(String filename) {
        try {
            File file = new File(filename);
            FileInputStream fis = new FileInputStream(file);
            BufferedInputStream bis = new BufferedInputStream(fis);
            final AdvancedPlayer player = new AdvancedPlayer(bis);

            // run in new thread to play in background
            new Thread() {
                public void run() {
                    try {
                        player.play(0, Integer.MAX_VALUE);
                    }
                    catch (Exception e) {
                        throw new RuntimeException(e.getMessage());
                    }
                }
            } .start();

        }
        catch (Exception ex) {
            StdOut.println(ex);
        }
    }


    public static void main(String[] args) {
        String filename = args[0];
        BackgroundMP3.play(filename);

        // do some computation while music is playing
        int n = 10000;
        double sum = 0.0;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                sum += Math.sin(i + j);
            }
            StdOut.println(i);
        }

        // if you want to exit when the code gets here
        System.exit(0);
    }

}


Copyright © 2000–2022, Robert Sedgewick and Kevin Wayne.
Last updated: Thu Aug 11 10:14:17 EDT 2022.