简体   繁体   中英

How do I play an mp3 file for both an application and applet?

I working on a program that both plays a sound when you click a button in an applet and in an application but I keep receiving an error while in the application portion of the program.

This is the error I get: sample.mp3 (The system cannot find the file specified) but I clearly have it in my project.

public class project extends JApplet {

public void init() {
    add(new AppletOrApplicationMainComponent());
}

public static void main(String args[]) {
    JFrame frame = new JFrame("");
    frame.getContentPane().add(new AppletOrApplicationMainComponent());
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.pack();
    frame.setVisible(true);
}
}

class AppletOrApplicationMainComponent extends JPanel {

public AppletOrApplicationMainComponent() {

    super(new BorderLayout());

    JButton button = new JButton("Play");
    button.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            Play();
        }
    });
    add(button, BorderLayout.SOUTH);
}

private void Play(){

    try{

        File file = new File("sample.mp3");
        FileInputStream fis = new FileInputStream(file);
        BufferedInputStream bis = new BufferedInputStream(fis);
        Player player = new Player(bis);
        player.play();

    }catch(Exception e){ 
        e.printStackTrace();
    }
}
}

In all that excitement, almost forgot to answer the question:

How do I play an mp3 file for both an application and applet?

Firstly, using URL to access a resource is compatible with both applet and application. The URL can be obtained from Class.getResource(String) . For more details on using the method, see the embedded resource info. page .

As to playing an MP3 for which we have an URL, see the MP3 decoding support section of the Java Sound info. page . Basically it boils down to adding an MP3 SPI to the run-time class-path of the app.

Also note that the Clip convenience class mentioned in that page (and shown in the example) does not work with large files. From memory, it will hold at most 1 second of CD quality (stereophonic, 16 bit, 44.1 KHz) sound. For larger files you might use an AudioInputStream directly, reading the bytes and feeding them back out to the sound API that plays them. Either that or use BigClip , which caches the entire stream bytes in memory, much like Clip .

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