FileDocCategorySizeDatePackage
AudioCaptureToDisk.javaAPI DocExample8180Wed Nov 10 12:54:28 GMT 2004com.oreilly.qtjnotebook.ch06

AudioCaptureToDisk.java

/*

Copyright (c) 2004, Chris Adamson

Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

*/
package com.oreilly.qtjnotebook.ch06;

import quicktime.*;
import quicktime.io.*;
import quicktime.std.*;
import quicktime.std.sg.*;
import quicktime.std.movies.*;
import quicktime.std.image.*;
import quicktime.qd.*;
import quicktime.sound.*;

import java.awt.*;
import java.awt.event.*;
import javax.swing.Timer;

import com.oreilly.qtjnotebook.ch01.QTSessionCheck;

public class AudioCaptureToDisk extends Frame 
    implements ItemListener, ActionListener {

    static final Dimension meterDim = new Dimension (200, 25);

    Choice deviceChoice;
    Checkbox previewCheck;
    AudioLevelMeter audioLevelMeter;
    SequenceGrabber grabber;
    SGSoundChannel soundChannel;
    SPBDevice inputDriver;
    boolean grabbing;
    Button stopButton;
    QTFile grabFile;

    public AudioCaptureToDisk() throws QTException {
        super ("Audio Record");
        QTSessionCheck.check();
        setLayout (new GridLayout (4, 1));
        deviceChoice = new Choice();
        deviceChoice.addItemListener (this);
        add (deviceChoice);
        previewCheck = new Checkbox ("Preview", false);
        previewCheck.addItemListener (this);
        add (previewCheck);
        audioLevelMeter = new AudioLevelMeter();
        add (audioLevelMeter);
        stopButton = new Button ("Stop");
        stopButton.addActionListener (this);
        add (stopButton);
        setUpAudioGrab();
        grabbing = true;
    }

    public void itemStateChanged (ItemEvent e) {
        try {
            if (e.getSource() == previewCheck) {
                if (previewCheck.getState())
                    soundChannel.setVolume (1.0f);
                else
                    soundChannel.setVolume (0.0f);
            } else if (e.getSource() == deviceChoice) {
                System.out.println ("changed device to "+
                                    deviceChoice.getSelectedItem());
                grabbing = false;
                soundChannel.setDevice (deviceChoice.getSelectedItem());
                // also reset inputDriver?
                inputDriver = soundChannel.getInputDriver();
                inputDriver.setLevelMeterOnOff (true);

                grabbing = true;
            }
        } catch (QTException qte) {
            qte.printStackTrace();
        }
    }

    public void actionPerformed (ActionEvent e) {
        if (e.getSource() == stopButton) {
            System.out.println ("Stop grabbing");
            try {
                if (grabber != null) {
                    grabber.stop();
                }
            } catch (QTException qte) {
                qte.printStackTrace();
            } finally {
                System.exit (0);
            }
        }
    }

    protected void setUpAudioGrab() throws QTException {
        grabber = new SequenceGrabber();
        System.out.println ("got grabber");
        soundChannel = new SGSoundChannel (grabber);
        System.out.println ("Got SGAudioChannel");
        System.out.println ("SGChannelInfo = " +
                            soundChannel.getSoundInputParameters());
        System.out.println ("SoundDescription = " + 
                            soundChannel.getSoundDescription());

        // create list of input devices
        // getDeviceList flags: http://developer.apple.com/documentation/QuickTime/APIREF/SOURCESIII/sggetchanneldevicelist.htm
        SGDeviceList devices = soundChannel.getDeviceList(StdQTConstants.sgDeviceListDontCheckAvailability);
        int deviceCount = devices.getCount();
        for (int i=0; i<deviceCount; i++) {
            SGDeviceName deviceName = devices.getDeviceName(i);
            // is it available?
            if ((deviceName.getFlags() &
                 StdQTConstants.sgDeviceNameFlagDeviceUnavailable) == 0)
            deviceChoice.add(deviceName.getName());
        }

        // prepare and start previewing
        // note - second prepare arg should seemingly be false,
        // but if it is, you get erroneous dskFulErr's
        grabber.prepare(true, false);
        soundChannel.setUsage (StdQTConstants.seqGrabPreview |
                               StdQTConstants.seqGrabRecord);
        soundChannel.setVolume (0.0f);

        // get settings
        // yikes! this crashes java 1.4.2 on mac os x!
        // soundChannel.settingsDialog();
        final SGSoundChannel sc = soundChannel;
        Thread t = new Thread() {
                public void run() {
                    try {
                        sc.settingsDialog();
                    } catch (QTException qte) {
                        qte.printStackTrace();
                    }
                }
            };
        t.start();
        while (t.isAlive())
            Thread.yield();

        grabber.startPreview();

        // create output file
        grabFile = new QTFile (new java.io.File ("audiograb.mov"));
        if (grabFile.exists())
            grabFile.delete();
        grabber.setDataOutput(grabFile,
                              StdQTConstants.seqGrabToDisk 
                              //seqGrabDontAddMovieResource);
                              );
        grabber.startRecord();

        inputDriver = soundChannel.getInputDriver();
        inputDriver.setLevelMeterOnOff (true);

        int[] levelTest = inputDriver.getActiveLevels();
        System.out.println (levelTest.length + " active levels");

        // set up thread to update level meter
        ActionListener timerCallback =
            new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    if (grabbing) {
                        try {
                            grabber.idle();
                            audioLevelMeter.repaint();
                        } catch (QTException qte) {
                            qte.printStackTrace();
                        }
                    }
                }
            };
        Timer timer = new Timer (50, timerCallback);
        timer.start();
    }

    public static void main (String[] args) {
        try {
            Frame f = new AudioCaptureToDisk();
            f.pack();
            f.setVisible(true);
        } catch (QTException qte) {
            qte.printStackTrace();
        }
    }

    public class AudioLevelMeter extends Canvas {
        public void paint (Graphics g) {
            // get current level if available
            int level = 0;
            if (inputDriver != null) {
                try {
                    int[] levels = inputDriver.getActiveLevels();
                    if (levels.length > 0)
                        level = levels[0];
                } catch (QTException qte) {
                    qte.printStackTrace();
                }
            }
            float levelPercent = level / 256f;
            System.out.println (level + ", " + levelPercent);
            // draw box
            g.setColor (Color.green);
            g.fillRect (0, 0,
                        (int) (levelPercent * getWidth()),
                        getHeight());
        }
        public Dimension getPreferredSize() { return meterDim; }
    }
}