能在applet中播放,就肯定能在application中放了,只有 javax.sound.sampled 等几个包,你可以看一下applet中的代码。

解决方案 »

  1.   


    再帖一个例子代码,从java.sun.com那里下的:import java.applet.AudioClip;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.net.URL;
    import java.net.MalformedURLException;
    import java.awt.GridBagLayout;public class SoundApplication extends JPanel
                                  implements ActionListener,
                                             ItemListener {
        SoundList soundList;
        String auFile = "spacemusic.au";
        String aiffFile = "flute+hrn+mrmba.aif";
        String midiFile = "trippygaia1.mid";
        String rmfFile = "jungle.rmf";
        String wavFile = "bottle-open.wav";
        String chosenFile;
            
        AudioClip onceClip, loopClip;
        URL codeBase;    JComboBox formats;
        JButton playButton, loopButton, stopButton;
        JLabel status;
            
        boolean looping = false;    public SoundApplication() {
            String [] fileTypes = {auFile,
                                   aiffFile,
                                   midiFile,        
                                   rmfFile,
                                   wavFile};
            formats = new JComboBox(fileTypes);
            formats.setSelectedIndex(0);
            chosenFile = (String)formats.getSelectedItem();
            formats.addItemListener(this);        playButton = new JButton("Play");
            playButton.addActionListener(this);        loopButton = new JButton("Loop");
            loopButton.addActionListener(this);        stopButton = new JButton("Stop");
            stopButton.addActionListener(this);
            stopButton.setEnabled(false);
            
            status = new JLabel(
                        "Click Play or Loop to play the selected sound file.");
                    
            JPanel controlPanel = new JPanel();
            controlPanel.add(formats);
            controlPanel.add(playButton);
            controlPanel.add(loopButton);
            controlPanel.add(stopButton);           
                    
            JPanel statusPanel = new JPanel();
            statusPanel.add(status);
                    
            add(controlPanel);
            add(statusPanel);        startLoadingSounds();
        }    public void itemStateChanged(ItemEvent e){
            chosenFile = (String)formats.getSelectedItem();
            soundList.startLoading(chosenFile);
        }    void startLoadingSounds() {
            //Start asynchronous sound loading.
            try {
                codeBase = new URL("file:" + System.getProperty("user.dir") + "/");
            } catch (MalformedURLException e) {
                System.err.println(e.getMessage());
            }
            soundList = new SoundList(codeBase);
            soundList.startLoading(auFile);
            soundList.startLoading(aiffFile);
            soundList.startLoading(midiFile);
            soundList.startLoading(rmfFile);
            soundList.startLoading(wavFile);
        }    public void stop() {
            onceClip.stop();        //Cut short the one-time sound.
            if (looping) {
                loopClip.stop();    //Stop the sound loop.
            }
        }        public void start() {
            if (looping) {
                loopClip.loop();    //Restart the sound loop.
            }
        }        public void actionPerformed(ActionEvent event) {
            //PLAY BUTTON
            Object source = event.getSource();
            if (source == playButton) {
                //Try to get the AudioClip.
                onceClip = soundList.getClip(chosenFile);
                stopButton.setEnabled(true);
                onceClip.play();     //Play it once.
                status.setText("Playing sound " + chosenFile + ".");
                if (onceClip == null) {
                    status.setText("Sound " + chosenFile + " not loaded yet.");
                }
                return;
            }        //START LOOP BUTTON
            if (source == loopButton) {
                loopClip = soundList.getClip(chosenFile);            looping = true;
                loopClip.loop();     //Start the sound loop.
                loopButton.setEnabled(false); //Disable start button.
                stopButton.setEnabled(true);
                status.setText("Playing sound " + chosenFile + " continuously.");
                if (loopClip == null) {
                    status.setText("Sound " + chosenFile + " not loaded yet.");
                }
                return;
            }        //STOP LOOP BUTTON
            if (source == stopButton) {
                if (looping) {
                    looping = false;
                    loopClip.stop();    //Stop the sound loop.
                    loopButton.setEnabled(true); //Enable start button.
                } else if (onceClip != null) {
                    onceClip.stop();
                }
                stopButton.setEnabled(false);
                status.setText("Stopped playing " + chosenFile + ".");
                return;
            }
        }    public static void main(String s[]) {
            WindowListener l = new WindowAdapter() {
                public void windowClosing(WindowEvent e) {System.exit(0);}
            };
            JFrame f = new JFrame("SoundApplication");
            f.addWindowListener(l);
            f.getContentPane().add(new SoundApplication());
            f.setSize(new Dimension(400,100));
            f.show();
        }
    }
      

  2.   


    上面的例子没有用javax.sound下的包,因为applet可以支持wav文件的播放,所以可以直接用它的java.applet.audioclip.*包。这也可以在application中使用,我说过了,没错吧。如果想提供很精细、复杂的声音、视频等支持,可以用JMF,这个就不是一两句话能说完的了,你可以去java.sun.com/products/jmf看看。
      

  3.   

    好人做到底,再帖一个javax.sound.sampled的例子吧:/*
     * @(#)JavaSound.java 1.15 00/01/31
     *
     * Copyright (c) 1999 Sun Microsystems, Inc. All Rights Reserved.
     *
     * Sun grants you ("Licensee") a non-exclusive, royalty free, license to use,
     * modify and redistribute this software in source and binary code form,
     * provided that i) this copyright notice and license appear on all copies of
     * the software; and ii) Licensee does not utilize the software in a manner
     * which is disparaging to Sun.
     *
     * This software is provided "AS IS," without a warranty of any kind. ALL
     * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING ANY
     * IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
     * NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN AND ITS LICENSORS SHALL NOT BE
     * LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING
     * OR DISTRIBUTING THE SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR ITS
     * LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT,
     * INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER
     * CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF
     * OR INABILITY TO USE SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
     * POSSIBILITY OF SUCH DAMAGES.
     *
     * This software is not designed or intended for use in on-line control of
     * aircraft, air traffic, aircraft navigation or aircraft communications; or in
     * the design, construction, operation or maintenance of any nuclear
     * facility. Licensee represents and warrants that it will not use or
     * redistribute the Software for such purposes.
     */
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.border.*;
    import java.io.File;
    import java.util.Vector;
    import javax.sound.sampled.*;
    import javax.sound.midi.*;
    /**
     * The Java Sound Samples : MidiSynth, Juke, CapturePlayback, Groove.
     *
     * @version @(#)JavaSound.java 1.15 00/01/31
     * @author Brian Lichtenwalter  
     */
    public class JavaSound extends JPanel implements ChangeListener, Runnable {    Vector demos = new Vector(4);
        JTabbedPane tabPane = new JTabbedPane();
        int width = 760, height = 500;
        int index;
        public JavaSound(String audioDirectory) {        setLayout(new BorderLayout());        JMenuBar menuBar = new JMenuBar();
           
            if (JavaSoundApplet.applet == null) {
                JMenu fileMenu = (JMenu) menuBar.add(new JMenu("File"));
                JMenuItem item = (JMenuItem) fileMenu.add(new JMenuItem("Exit"));
                item.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent e) { System.exit(0); }
                });
            }
            JMenu options = (JMenu) menuBar.add(new JMenu("Options"));
            JMenuItem item = (JMenuItem) options.add(new JMenuItem("Applet Info"));
            item.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) { showInfoDialog(); }
            });
            add(menuBar, BorderLayout.NORTH);        tabPane.addChangeListener(this);        EmptyBorder eb = new EmptyBorder(5,5,5,5);
            BevelBorder bb = new BevelBorder(BevelBorder.LOWERED);
            CompoundBorder cb = new CompoundBorder(eb,bb);
            JPanel p = new JPanel(new BorderLayout());
            p.setBorder(new CompoundBorder(cb,new EmptyBorder(0,0,90,0)));
            final Juke juke = new Juke(audioDirectory);
            p.add(juke);
            demos.add(juke);
            tabPane.addTab("Juke Box", p);        new Thread(this).start();        add(tabPane, BorderLayout.CENTER);
        }
        public void stateChanged(ChangeEvent e) {
            close();
            System.gc();
            index = tabPane.getSelectedIndex();
            open();
        }
        public void close() {
            ((ControlContext) demos.get(index)).close();
        }
        public void open() {
            ((ControlContext) demos.get(index)).open();
        }
        public Dimension getPreferredSize() {
            return new Dimension(width, height);
        }
        public static void showInfoDialog() {
            final String msg = 
                "When running the Java Sound demo as an applet these permissions\n" +
                "are necessary in order to load/save files and record audio :  \n\n"+
                "grant { \n" +
                "  permission java.io.FilePermission \"<<ALL FILES>>\", \"read, write\";\n" +
                "  permission javax.sound.sampled.AudioPermission \"record\"; \n" +
                "  permission java.util.PropertyPermission \"user.dir\", \"read\";\n"+
                "}; \n\n" +
                "The permissions need to be added to the .java.policy file.";
            new Thread(new Runnable() {
                public void run() {
                    JOptionPane.showMessageDialog(null, msg, "Applet Info", JOptionPane.INFORMATION_MESSAGE);
                }
            }).start();
        }    /**
         * Lazy load the tabbed pane with CapturePlayback, MidiSynth and Groove.
         */
        public void run() {
            EmptyBorder eb = new EmptyBorder(5,5,5,5);
            BevelBorder bb = new BevelBorder(BevelBorder.LOWERED);
            CompoundBorder cb = new CompoundBorder(eb,bb);
            JPanel p = new JPanel(new BorderLayout());
            p.setBorder(new CompoundBorder(cb,new EmptyBorder(0,0,90,0)));
            CapturePlayback capturePlayback = new CapturePlayback();
            demos.add(capturePlayback);
            p.add(capturePlayback);
            tabPane.addTab("Capture/Playback", p);        MidiSynth midiSynth = new MidiSynth();
            demos.add(midiSynth);
            tabPane.addTab("Midi Synthesizer", midiSynth);        p = new JPanel(new BorderLayout());
            p.setBorder(new CompoundBorder(cb,new EmptyBorder(0,0,5,20)));
            Groove groove = new Groove();
            demos.add(groove);
            p.add(groove);
            tabPane.addTab("Groove Box", p);
        }
        public static void main(String[] args) {        try { 
                if (MidiSystem.getSequencer() == null) {
                    System.err.println("MidiSystem Sequencer Unavailable, exiting!");
                    System.exit(1);
                } else if (AudioSystem.getMixer(null) == null) {
                    System.err.println("AudioSystem Unavailable, exiting!");
                    System.exit(1);
                }
            } catch (Exception ex) { ex.printStackTrace(); System.exit(1); }        String media = "./audio";
            if (args.length > 0) {
                File file = new File(args[0]);
                if (file == null && !file.isDirectory()) {
                    System.out.println("usage: java JavaSound audioDirectory");
                } else {
                    media = args[0];
                }
            }        final JavaSound demo = new JavaSound(media);
            JFrame f = new JFrame("Java Sound Demo");
            f.addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent e) {System.exit(0);}
                public void windowDeiconified(WindowEvent e) { demo.open(); }
                public void windowIconified(WindowEvent e) { demo.close(); }
            });
            f.getContentPane().add("Center", demo);
            f.pack();
            Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
            f.setLocation(d.width/2 - demo.width/2, d.height/2 - demo.height/2);
            f.setSize(new Dimension(demo.width, demo.height));
            f.setVisible(true);
        }
    }