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

📄 juke.java

📁 用JAVA实现录音机功能
💻 JAVA
📖 第 1 页 / 共 3 页
字号:
/* * @(#)Juke.java	1.19	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.font.*;import java.awt.geom.*;import java.awt.event.*;import java.text.AttributedString;import java.text.AttributedCharacterIterator;import javax.swing.*;import javax.swing.border.*;import javax.swing.table.*;import javax.swing.event.*;import javax.sound.midi.*;import javax.sound.sampled.*;import java.io.File;import java.io.InputStream;import java.io.FileInputStream;import java.io.BufferedInputStream;import java.util.Vector;import java.net.URL;/** * A JukeBox for sampled and midi sound files.  Features duration progress,  * seek slider, pan and volume controls. * * @version @(#)Juke.java	1.19 00/01/31 * @author Brian Lichtenwalter   */public class Juke extends JPanel implements Runnable, LineListener, MetaEventListener, ControlContext {    final int bufSize = 16384;    PlaybackMonitor playbackMonitor = new PlaybackMonitor();    Vector sounds = new Vector();    Thread thread;    Sequencer sequencer;    boolean midiEOM, audioEOM;    Synthesizer synthesizer;    MidiChannel channels[];     Object currentSound;    String currentName;    double duration;    int num;    boolean bump;    boolean paused = false;    JButton startB, pauseB, loopB, prevB, nextB;    JTable table;    JSlider panSlider, gainSlider;    JSlider seekSlider;    JukeTable jukeTable;    Loading loading;    Credits credits;    String errStr;    JukeControls controls;    public Juke(String dirName) {        setLayout(new BorderLayout());        setBorder(new EmptyBorder(5,5,5,5));        if (dirName != null) {            loadJuke(dirName);         }        JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,             jukeTable = new JukeTable(), controls = new JukeControls());        splitPane.setContinuousLayout(true);        add(splitPane);    }    public void open() {        try {            sequencer = MidiSystem.getSequencer();			if (sequencer instanceof Synthesizer) {				synthesizer = (Synthesizer)sequencer;				channels = synthesizer.getChannels();			}         } catch (Exception ex) { ex.printStackTrace(); return; }        sequencer.addMetaEventListener(this);        (credits = new Credits()).start();    }    public void close() {        if (credits != null && credits.isAlive()) {            credits.interrupt();        }        if (thread != null && startB != null) {            startB.doClick(0);        }        if (jukeTable != null && jukeTable.frame != null) {            jukeTable.frame.dispose();            jukeTable.frame = null;        }        if (sequencer != null) {            sequencer.close();        }    }    public void loadJuke(String name) {        try {            File file = new File(name);            if (file != null && file.isDirectory()) {                String files[] = file.list();                for (int i = 0; i < files.length; i++) {                    File leafFile = new File(file.getAbsolutePath(), files[i]);                    if (leafFile.isDirectory()) {                        loadJuke(leafFile.getAbsolutePath());                    } else {                        addSound(leafFile);                    }                }            } else if (file != null && file.exists()) {                addSound(file);            }        } catch (SecurityException ex) {            reportStatus(ex.toString());            JavaSound.showInfoDialog();        } catch (Exception ex) {            reportStatus(ex.toString());        }    }    private void addSound(File file) {        String s = file.getName();        if (s.endsWith(".au") || s.endsWith(".rmf") ||            s.endsWith(".mid") || s.endsWith(".wav") ||            s.endsWith(".aif") || s.endsWith(".aiff"))        {            sounds.add(file);        }    }    public boolean loadSound(Object object) {        duration = 0.0;        (loading = new Loading()).start();        if (object instanceof URL) {            currentName = ((URL) object).getFile();            playbackMonitor.repaint();            try {                currentSound = AudioSystem.getAudioInputStream((URL) object);            } catch(Exception e) {                try {                     currentSound = MidiSystem.getSequence((URL) object);		} catch (InvalidMidiDataException imde) {		    System.out.println("Unsupported audio file.");		    return false;                } catch (Exception ex) {                     ex.printStackTrace(); 		    currentSound = null;		    return false;                }            }        } else if (object instanceof File) {            currentName = ((File) object).getName();            playbackMonitor.repaint();            try {                currentSound = AudioSystem.getAudioInputStream((File) object);            } catch(Exception e1) {                // load midi & rmf as inputstreams for now                //try {                     //currentSound = MidiSystem.getSequence((File) object);                //} catch (Exception e2) {                     try {                         FileInputStream is = new FileInputStream((File) object);                        currentSound = new BufferedInputStream(is, 1024);                    } catch (Exception e3) {                         e3.printStackTrace(); 			currentSound = null;			return false;                    }                //}            }        }        loading.interrupt();        // user pressed stop or changed tabs while loading        if (sequencer == null) {            currentSound = null;            return false;        }         if (currentSound instanceof AudioInputStream) {           try {                AudioInputStream stream = (AudioInputStream) currentSound;                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))                 {                    AudioFormat tmp = new AudioFormat(                                              AudioFormat.Encoding.PCM_SIGNED,                                               format.getSampleRate(),                                              format.getSampleSizeInBits() * 2,                                              format.getChannels(),                                              format.getFrameSize() * 2,                                              format.getFrameRate(),                                              true);                    stream = AudioSystem.getAudioInputStream(tmp, stream);                    format = tmp;                }                DataLine.Info info = new DataLine.Info(                                          Clip.class,                                           stream.getFormat(),                                           ((int) stream.getFrameLength() *                                              format.getFrameSize()));                Clip clip = (Clip) AudioSystem.getLine(info);                clip.addLineListener(this);                clip.open(stream);                currentSound = clip;                seekSlider.setMaximum((int) stream.getFrameLength());            } catch (Exception ex) { 		ex.printStackTrace(); 		currentSound = null;		return false;	    }        } else if (currentSound instanceof Sequence || currentSound instanceof BufferedInputStream) {            try {                sequencer.open();                if (currentSound instanceof Sequence) {                    sequencer.setSequence((Sequence) currentSound);                } else {                    sequencer.setSequence((BufferedInputStream) currentSound);                }				seekSlider.setMaximum((int)(sequencer.getMicrosecondLength() / 1000));            } catch (InvalidMidiDataException imde) { 		System.out.println("Unsupported audio file.");		currentSound = null;		return false;            } catch (Exception ex) { 		ex.printStackTrace(); 		currentSound = null;		return false;	    }        }        seekSlider.setValue(0);        		// enable seek, pan, and gain sliders for sequences as well as clips		seekSlider.setEnabled(true);		panSlider.setEnabled(true);        gainSlider.setEnabled(true);        			duration = getDuration();	return true;    }    public void playSound() {        playbackMonitor.start();        setGain();        setPan();        midiEOM = audioEOM = bump = false;        if (currentSound instanceof Sequence || currentSound instanceof BufferedInputStream && thread != null) {            sequencer.start();            while (!midiEOM && thread != null && !bump) {                try { thread.sleep(99); } catch (Exception e) {break;}            }            sequencer.stop();            sequencer.close();        } else if (currentSound instanceof Clip && thread != null) {            Clip clip = (Clip) currentSound;            clip.start();            try { thread.sleep(99); } catch (Exception e) { }            while ((paused || clip.isActive()) && thread != null && !bump) {                try { thread.sleep(99); } catch (Exception e) {break;}            }            clip.stop();            clip.close();        }        currentSound = null;        playbackMonitor.stop();    }    public double getDuration() {        double duration = 0.0;        if (currentSound instanceof Sequence) {            duration = ((Sequence) currentSound).getMicrosecondLength() / 1000000.0;        }  else if (currentSound instanceof BufferedInputStream) {			duration = sequencer.getMicrosecondLength() / 1000000.0;		} else if (currentSound instanceof Clip) {            Clip clip = (Clip) currentSound;            duration = clip.getBufferSize() /                 (clip.getFormat().getFrameSize() * clip.getFormat().getFrameRate());        }         return duration;    }    public double getSeconds() {        double seconds = 0.0;

⌨️ 快捷键说明

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