⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 soundplayer.java

📁 这是一种java小应用程序编写的游戏
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
/*
 * SoundPlayer.java
 * Created on March 10, 2001, 4:23 PM
 */
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.sound.midi.*;
import javax.sound.sampled.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.BufferedInputStream;
import java.util.Vector;
import java.net.URL;

/**
 * This class is used to play sound files.
 *
 * @author Sammy Leong
 * @version 1.0
 */
public class SoundPlayer extends JPanel
implements Runnable, LineListener, MetaEventListener, ActionListener
{
    /** sound object list */
    public Vector sounds = new Vector();
    /** thread used to play the sound */
    private Thread thread;
    /** sound sequencer */
    private Sequencer sequencer;
    /** flag: playing midi or audio file */
    private boolean midiEOM, audioEOM;
    /** sound synthesizer */
    private Synthesizer synthesizer;
    /** channel objects for playing midi */
    private MidiChannel channels[];
    /** current playing sound */
    private Object currentSound;
    /** current sound name */
    private String currentName;
    /** sound list offset */
    private int num = -1;
    /** flag: change of sound */
    private boolean bump;
    /** flag: paused or not */
    private boolean paused = false;
    /** flag: loop or not */
    public boolean loop = true;
    /** volumn */
    private int volumn = 100;
    /** control buttons */
    JButton startB, pauseB, prevB, nextB;

    /**
     * Construct a sound player with directory name of music files.
     * @param dirName directory with sound files
     */
    public SoundPlayer(String dirName)
    {
        if (dirName != null)
        {
            /** load the sound files */
            loadFile(dirName);
        }

        /** create control buttons the panel */
        JPanel jp = new JPanel(new GridLayout(4, 1));
        /** create the buttons */
        startB = addButton("Start", jp, sounds.size() != 0);
        pauseB = addButton("Pause", jp, false);
        prevB = addButton("<<", jp, false);
        nextB = addButton(">>", jp, false);
    }

    /**
     * Create a button.
     * @param name name of button
     * @param panel container of button
     * @param state enabled or disabled
     */
    private JButton addButton(String name, JPanel panel, boolean state)
    {
        /** create the button */
        JButton b = new JButton(name);
        /** add action handler */
        b.addActionListener(this);
        /** set state */
        b.setEnabled(state);
        if (panel != null)
            /** add it to the container */
            panel.add(b);
        /** return the button */
        return b;
    }

    /**
     * Create and open the sequencer.
     */
    public void open()
    {
        try
        {
            /** get the system sequencer */
            sequencer = MidiSystem.getSequencer();
            if (sequencer instanceof Synthesizer)
            {
                synthesizer = (Synthesizer)sequencer;
                /** get the system channels */
                channels = synthesizer.getChannels();
            }
        }
        catch (Exception e)
        {
            return;
        }
        /** add the meta event listener */
        sequencer.addMetaEventListener(this);
    }

    /**
     * Close the sequencer.
     */
    public void close()
    {
        /** if a sound is playing */
        if (thread != null && startB != null)
        {
            /** stop playing */
            startB.doClick(0);
        }
        /** if the sequencer is opened */
        if (sequencer != null)
        {
            /** close it */
            sequencer.close();
        }
    }

    /**
     * Loads all sound files ina directory.
     * @param name directory name
     */
    public void loadFile(String name)
    {
        try
        {
            /** create the file object */
            File file = new File(name);
            /** if the object is a directory */
            if (file != null && file.isDirectory())
            {
                /** get the list of files in the directory */
                String files[] = file.list();
                /** iterate through the list */
                for (int i = 0; i < files.length; i++)
                {
                    /** get the path */
                    File leafFile = new File(file.getAbsolutePath(), files[i]);
                    /** if it's a directory */
                    if (leafFile.isDirectory())
                    {
                        /** recurse into the directory */
                        loadFile(leafFile.getAbsolutePath());
                    }
                    /** if it's a file */
                    else
                    {
                        /** load the file */
                        addSound(leafFile);
                    }
                }
            }
            /** if the object is a file and it exists */
            else if (file != null && file.exists())
            {
                /** load the file */
                addSound(file);
            }
        }
        catch (Exception e)
        {
        }
    }

    /**
     * Attemps to add a sound file.
     * @param file file object to add
     */
    private void addSound(File file)
    {
        String s = file.getName();
        /** if the file has right extension */
        if (s.endsWith(".au") || s.endsWith(".rmf") ||
        s.endsWith(".mid") || s.endsWith(".wav") ||
        s.endsWith(".aif") || s.endsWith(".aiff"))
        {
            /** add the file */
            sounds.add(file);
        }
    }

    /**
     * Loads a sound object.
     * @param object sound object to load
     */
    public boolean loadSound(Object object)
    {
        /** if the object is a URL object */
        if (object instanceof URL)
        {
            /** get the file name */
            currentName = ((URL) object).getFile();
            try
            {
                /** try to create an audio sound object */
                currentSound = AudioSystem.getAudioInputStream((URL) object);
            }
            /** if it's not an audio sound object */
            catch(Exception e)
            {
                try
                {
                    /** try to create a midi sound object */
                    currentSound = MidiSystem.getSequence((URL) object);
                }
                /** if it's not a midi sound object neither */
                catch (InvalidMidiDataException e1)
                {
                }
                catch (Exception e2)
                {
                }
            }
        }
        /** if the object is a File object */
        else if (object instanceof File)
        {
            /** get the file name */
            currentName = ((File) object).getName();
            try
            {
                /** try to create an audio sound object */
                currentSound = AudioSystem.getAudioInputStream((File) object);
            }
            /** if it's not an audio sound object */
            catch(Exception e)
            {
                /** load midi & rmf as inputstreams for now */
                //try {
                //currentSound = MidiSystem.getSequence((File) object);
                //} catch (Exception e2) {
                try
                {
                    /** open the file */
                    FileInputStream is = new FileInputStream((File) object);
                    /** try to create a midi sound object */
                    currentSound = new BufferedInputStream(is, 1024);
                }
                catch (Exception e1)
                {
                }
                //}
            }
        }

        /** if no sequencer available */
        if (sequencer == null)
        {
            /** set sound object to null */
            currentSound = null;
            /** and otta here */
            return false;
        }

        /** if the sound object is an AudioInputStream object */
        if (currentSound instanceof AudioInputStream)
        {
            try
            {
                /** create the stream */
                AudioInputStream stream = (AudioInputStream) currentSound;
                /** create the file format object */
                AudioFormat format = stream.getFormat();

                /**
                 * we can't yet open the device for ALAW/ULAW playback,
                 * convert ALAW/ULAW to PCM
                 */
                if ((format.getEncoding() == AudioFormat.Encoding.ULAW) ||
                (format.getEncoding() == AudioFormat.Encoding.ALAW))
                {
                    /** setup the format */
                    AudioFormat tmp = new AudioFormat(
                    AudioFormat.Encoding.PCM_SIGNED,
                    format.getSampleRate(), format.getSampleSizeInBits() * 2,
                    format.getChannels(), format.getFrameSize() * 2,
                    format.getFrameRate(), true);
                    /** open the stream with specified format */
                    stream = AudioSystem.getAudioInputStream(tmp, stream);
                    /** store the formst for later use */
                    format = tmp;
                }
                /** create the line to play the sound */
                DataLine.Info info = new DataLine.Info( Clip.class,
                stream.getFormat(), ((int) stream.getFrameLength() *
                format.getFrameSize()));

                /** convert the sound into a clip */
                Clip clip = (Clip) AudioSystem.getLine(info);
                clip.addLineListener(this);
                clip.open(stream);
                /** store the clip */
                currentSound = clip;
            }
            catch (Exception e)
            {
            }
        }
        /** if the sound object is a sequence */
        else if (currentSound instanceof Sequence ||
        currentSound instanceof BufferedInputStream)
        {
            try
            {
                /** open the sequencer */
                sequencer.open();
                /** if the object is a sequence */
                if (currentSound instanceof Sequence)
                {
                    /** set the sequence to the sequencer */
                    sequencer.setSequence((Sequence) currentSound);
                }
                /** if the object is a buffered input stream */
                else
                {
                    /** set the stream to the sequencer */
                    sequencer.setSequence((BufferedInputStream) currentSound);
                }
            }
            catch (InvalidMidiDataException imde)
            {
                return false;
            }
            catch (Exception ex)
            {
                return false;
            }
        }
        /** otta here */
        return true;
    }

    /**
     * Plays the current sound object.
     */
    public void playSound() {
        /** set volumn */
        setGain(volumn);
        /** set pan */
        setPan();
        /** reset flags to false */
        midiEOM = audioEOM = bump = false;
        /** if object is a sequencer */
        if (currentSound instanceof Sequence
        || currentSound instanceof BufferedInputStream && thread != null)
        {
            /** play the sound */
            sequencer.start();
            /** iterate */
            while (!midiEOM && thread != null && !bump)
            {
                try
                {
                    thread.sleep(99);
                }
                catch (Exception e)
                {
                    break;
                }
            }
            /** stop playing */
            sequencer.stop();
            /** close the sequencer */
            sequencer.close();
        }
        /** if the current sound object is a clip */
        else if (currentSound instanceof Clip && thread != null)
        {
            /** get the clip */

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -