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

📄 captureplayback.java

📁 用JAVA实现录音机功能
💻 JAVA
📖 第 1 页 / 共 3 页
字号:
/* * @(#)CapturePlayback.java	1.11	99/12/03 * * 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 java.awt.geom.Line2D;import javax.swing.*;import javax.swing.event.*;import javax.swing.border.*;import java.util.Vector;import java.util.Enumeration;import java.io.*;import javax.sound.sampled.*;import java.awt.font.*;import java.text.*;/** *  Capture/Playback sample.  Record audio in different formats *  and then playback the recorded audio.  The captured audio can  *  be saved either as a WAVE, AU or AIFF.  Or load an audio file *  for streaming playback. * * @version @(#)CapturePlayback.java	1.11	99/12/03 * @author Brian Lichtenwalter   */public class CapturePlayback extends JPanel implements ActionListener, ControlContext {    final int bufSize = 16384;    FormatControls formatControls = new FormatControls();    Capture capture = new Capture();    Playback playback = new Playback();    AudioInputStream audioInputStream;    SamplingGraph samplingGraph;    JButton playB, captB, pausB, loadB;    JButton auB, aiffB, waveB;    JTextField textField;    String fileName = "untitled";    String errStr;    double duration, seconds;    File file;    Vector lines = new Vector();    public CapturePlayback() {        setLayout(new BorderLayout());        EmptyBorder eb = new EmptyBorder(5,5,5,5);        SoftBevelBorder sbb = new SoftBevelBorder(SoftBevelBorder.LOWERED);        setBorder(new EmptyBorder(5,5,5,5));        JPanel p1 = new JPanel();        p1.setLayout(new BoxLayout(p1, BoxLayout.X_AXIS));        p1.add(formatControls);        JPanel p2 = new JPanel();        p2.setBorder(sbb);        p2.setLayout(new BoxLayout(p2, BoxLayout.Y_AXIS));        JPanel buttonsPanel = new JPanel();        buttonsPanel.setBorder(new EmptyBorder(10,0,5,0));        playB = addButton("Play", buttonsPanel, false);        captB = addButton("Record", buttonsPanel, true);        pausB = addButton("Pause", buttonsPanel, false);        loadB = addButton("Load...", buttonsPanel, true);        p2.add(buttonsPanel);        JPanel samplingPanel = new JPanel(new BorderLayout());        eb = new EmptyBorder(10,20,20,20);        samplingPanel.setBorder(new CompoundBorder(eb, sbb));        samplingPanel.add(samplingGraph = new SamplingGraph());        p2.add(samplingPanel);        JPanel savePanel = new JPanel();        savePanel.setLayout(new BoxLayout(savePanel, BoxLayout.Y_AXIS));             JPanel saveTFpanel = new JPanel();        saveTFpanel.add(new JLabel("File to save:  "));        saveTFpanel.add(textField = new JTextField(fileName));        textField.setPreferredSize(new Dimension(140,25));        savePanel.add(saveTFpanel);        JPanel saveBpanel = new JPanel();        auB = addButton("Save AU", saveBpanel, false);        aiffB = addButton("Save AIFF", saveBpanel, false);        waveB = addButton("Save WAVE", saveBpanel, false);        savePanel.add(saveBpanel);        p2.add(savePanel);        p1.add(p2);        add(p1);    }    public void open() { }    public void close() {        if (playback.thread != null) {            playB.doClick(0);        }        if (capture.thread != null) {            captB.doClick(0);        }    }    private JButton addButton(String name, JPanel p, boolean state) {        JButton b = new JButton(name);        b.addActionListener(this);        b.setEnabled(state);        p.add(b);        return b;    }    public void actionPerformed(ActionEvent e) {        Object obj = e.getSource();        if (obj.equals(auB)) {            saveToFile(textField.getText().trim(), AudioFileFormat.Type.AU);        } else if (obj.equals(aiffB)) {            saveToFile(textField.getText().trim(), AudioFileFormat.Type.AIFF);        } else if (obj.equals(waveB)) {            saveToFile(textField.getText().trim(), AudioFileFormat.Type.WAVE);        } else if (obj.equals(playB)) {            if (playB.getText().startsWith("Play")) {                playback.start();                samplingGraph.start();                captB.setEnabled(false);                pausB.setEnabled(true);                playB.setText("Stop");            } else {                playback.stop();                samplingGraph.stop();                captB.setEnabled(true);                pausB.setEnabled(false);                playB.setText("Play");            }        } else if (obj.equals(captB)) {            if (captB.getText().startsWith("Record")) {                file = null;                capture.start();                fileName = "untitled";                samplingGraph.start();                loadB.setEnabled(false);                playB.setEnabled(false);                pausB.setEnabled(true);                auB.setEnabled(false);                aiffB.setEnabled(false);                waveB.setEnabled(false);                captB.setText("Stop");            } else {                lines.removeAllElements();                  capture.stop();                samplingGraph.stop();                loadB.setEnabled(true);                playB.setEnabled(true);                pausB.setEnabled(false);                auB.setEnabled(true);                aiffB.setEnabled(true);                waveB.setEnabled(true);                captB.setText("Record");            }        } else if (obj.equals(pausB)) {            if (pausB.getText().startsWith("Pause")) {                if (capture.thread != null) {                    capture.line.stop();                } else {                    if (playback.thread != null) {                        playback.line.stop();                    }                }                pausB.setText("Resume");            } else {                if (capture.thread != null) {                    capture.line.start();                } else {                    if (playback.thread != null) {                        playback.line.start();                    }                }                pausB.setText("Pause");            }        } else if (obj.equals(loadB)) {            try {                File file = new File(System.getProperty("user.dir"));                JFileChooser fc = new JFileChooser(file);                fc.setFileFilter(new javax.swing.filechooser.FileFilter () {                    public boolean accept(File f) {                        if (f.isDirectory()) {                            return true;                        }                        String name = f.getName();                        if (name.endsWith(".au") || name.endsWith(".wav") || name.endsWith(".aiff") || name.endsWith(".aif")) {                            return true;                        }                        return false;                    }                    public String getDescription() {                        return ".au, .wav, .aif";                    }                });                if (fc.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {                    createAudioInputStream(fc.getSelectedFile(), true);                }            } catch (SecurityException ex) {                 JavaSound.showInfoDialog();                ex.printStackTrace();            } catch (Exception ex) {                 ex.printStackTrace();            }        }    }    public void createAudioInputStream(File file, boolean updateComponents) {        if (file != null && file.isFile()) {            try {                this.file = file;                errStr = null;                audioInputStream = AudioSystem.getAudioInputStream(file);                playB.setEnabled(true);                fileName = file.getName();                long milliseconds = (long)((audioInputStream.getFrameLength() * 1000) / audioInputStream.getFormat().getFrameRate());                duration = milliseconds / 1000.0;                auB.setEnabled(true);                aiffB.setEnabled(true);                waveB.setEnabled(true);                if (updateComponents) {                    formatControls.setFormat(audioInputStream.getFormat());                    samplingGraph.createWaveForm(null);                }            } catch (Exception ex) {                 reportStatus(ex.toString());            }        } else {            reportStatus("Audio file required.");        }    }    public void saveToFile(String name, AudioFileFormat.Type fileType) {        if (audioInputStream == null) {            reportStatus("No loaded audio to save");            return;        } else if (file != null) {            createAudioInputStream(file, false);        }        // reset to the beginnning of the captured data        try {            audioInputStream.reset();        } catch (Exception e) {             reportStatus("Unable to reset stream " + e);            return;        }        File file = new File(fileName = name);        try {            if (AudioSystem.write(audioInputStream, fileType, file) == -1) {                throw new IOException("Problems writing to file");            }        } catch (Exception ex) { reportStatus(ex.toString()); }        samplingGraph.repaint();    }            private void reportStatus(String msg) {

⌨️ 快捷键说明

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