FileDocCategorySizeDatePackage
AddAudioTrackQTEditor.javaAPI DocExample16199Wed Nov 10 12:50:20 GMT 2004com.oreilly.qtjnotebook.ch03

AddAudioTrackQTEditor.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.ch03;

import quicktime.*;
import quicktime.qd.QDRect;
import quicktime.std.*;
import quicktime.std.movies.*;
import quicktime.std.movies.media.*;
import quicktime.app.view.*;
import quicktime.io.*;
import quicktime.util.*;

import java.io.File;
import java.awt.*;
import java.awt.event.*;
import javax.swing.undo.*;
import javax.swing.JOptionPane;

import com.oreilly.qtjnotebook.ch01.QTSessionCheck;

public class AddAudioTrackQTEditor extends Frame
    implements ActionListener {

    Component comp;
    QTFile file;
    
    Movie movie;
    MovieController controller;
    Menu fileMenu, editMenu;
    MenuItem openItem, closeItem, newItem, quitItem;
    MenuItem copyItem, cutItem, pasteItem;
    MenuItem undoItem, redoItem;
    MenuItem saveItem, flattenItem;
    MenuItem addAudioTrackItem;
    static int newFrameX = -1;
    static int newFrameY = -1;
    static int windowCount = 0;

    UndoManager undoManager = new UndoManager();
    
    /** no-arg constructor for "new" movie
     */
    public AddAudioTrackQTEditor () throws QTException {
        super ("AddAudioTrackQTEditor");
        setLayout (new BorderLayout());
        QTSessionCheck.check();
        movie = new Movie(StdQTConstants.newMovieActive);
        controller = new MovieController (movie);
        controller.enableEditing(true);
        doMyLayout();
    }

    /** file-based constructor for opening movies
     */
    public AddAudioTrackQTEditor (QTFile file) throws QTException {
        super ("AddAudioTrackQTEditor");
        this.file = file;
        setLayout (new BorderLayout());
        QTSessionCheck.check();
        OpenMovieFile omf = OpenMovieFile.asRead (file);
        movie = Movie.fromFile (omf);
        controller = new MovieController (movie);
        controller.enableEditing(true);
        doMyLayout();
    }

    /** gets component from controller, makes menus
     */
    private void doMyLayout() throws QTException {
        // add movie component
        QTComponent qtc =
            QTFactory.makeQTComponent (controller);
        comp = qtc.asComponent();
        add (comp, BorderLayout.CENTER);
        // file menu
        fileMenu = new Menu ("File");
        newItem = new MenuItem ("New Movie");
        newItem.addActionListener (this);
        fileMenu.add (newItem);
        openItem = new MenuItem ("Open Movie...");
        openItem.addActionListener (this);
        fileMenu.add (openItem);
        closeItem = new MenuItem ("Close");
        closeItem.addActionListener (this);
        fileMenu.add (closeItem);
        saveItem = new MenuItem ("Save");
        saveItem.addActionListener (this);
        fileMenu.add (saveItem);
        flattenItem = new MenuItem ("Flatten");
        flattenItem.addActionListener (this);
        fileMenu.add (flattenItem);
        fileMenu.addSeparator();
        quitItem = new MenuItem ("Quit");
        quitItem.addActionListener (this);
        fileMenu.add(quitItem);
        // edit menu
        editMenu = new Menu ("Edit");
        undoItem = new MenuItem ("Undo");
        undoItem.addActionListener(this);
        editMenu.add(undoItem);
        redoItem = new MenuItem ("Redo");
        redoItem.addActionListener(this);
        editMenu.add(redoItem);
        editMenu.addSeparator();
        copyItem = new MenuItem ("Copy");
        copyItem.addActionListener(this);
        editMenu.add(copyItem);
        cutItem = new MenuItem ("Cut");
        cutItem.addActionListener(this);
        editMenu.add(cutItem);
        pasteItem = new MenuItem ("Paste");
        pasteItem.addActionListener(this);
        editMenu.add(pasteItem);
        editMenu.addSeparator();
        addAudioTrackItem = new MenuItem ("Add Audio Track...");
        addAudioTrackItem.addActionListener(this);
        editMenu.add(addAudioTrackItem);
        // make menu bar
        MenuBar bar = new MenuBar();
        bar.add (fileMenu);
        bar.add (editMenu);
        setMenuBar (bar);
        // add close-button handling
        addWindowListener (new WindowAdapter() {
                public void windowClosing (WindowEvent e) {
                    doClose();
                }
            });
    }

    /** handles menu actions
     */
    public void actionPerformed (ActionEvent e) {
        Object source = e.getSource();
        try {
            if (source == quitItem) doQuit();
            else if (source == openItem) doOpen();
            else if (source == closeItem) doClose();
            else if (source == saveItem) doSave();
            else if (source == flattenItem) doFlatten();
            else if (source == newItem) doNew();
            else if (source == copyItem) doCopy();
            else if (source == cutItem) doCut();
            else if (source == pasteItem) doPaste();
            else if (source == undoItem) doUndo();
            else if (source == redoItem) doRedo();
            else if (source == addAudioTrackItem) doAddAudioTrack();
        } catch (QTException qte) {
            qte.printStackTrace();
        }
    }

    public void doQuit() {
        System.exit(0);
    }

    public void doNew() throws QTException {
        makeNewAndShow();
    }

    public void doOpen() throws QTException {
        QTFile file =
            QTFile.standardGetFilePreview (QTFile.kStandardQTFileTypes);
        Frame f = new AddAudioTrackQTEditor (file);
        f.pack();
        if (newFrameX >= 0)
            f.setLocation (newFrameX+=16, newFrameY+=16);
        f.setVisible(true);
        windowCount++;
    }

    public void doClose() {
        setVisible(false);
        dispose();
        // quit if no windows now showing
        if (--windowCount == 0)
            doQuit();
    }

    public void doSave() throws QTException {
        // if no home file, then prompt for one
        if (file == null) {
            FileDialog fd = new FileDialog (this,
                                            "Save...",
                                            FileDialog.SAVE);
            fd.setVisible(true); // blocks
            if ((fd.getDirectory() == null) ||
                (fd.getFile() == null))
                return;
            file = new QTFile (new File (fd.getDirectory(),
                                         fd.getFile()));
        }
        int flags = StdQTConstants.createMovieFileDeleteCurFile |
                    StdQTConstants.createMovieFileDontCreateResFile |
                    StdQTConstants.showUserSettingsDialog;
        movie.convertToFile (file, // file
                             StdQTConstants.kQTFileTypeMovie, // filetype,
                             StdQTConstants.kMoviePlayer, // creator
                             IOConstants.smSystemScript, // scriptTag
                             flags);
    }


    public void doFlatten() throws QTException {
        // always attempts to save to a new location,
        // so prompt for filename
        FileDialog fd = new FileDialog (this,
                                        "Flatten...",
                                        FileDialog.SAVE);
        fd.setVisible(true); // blocks
        if ((fd.getDirectory() == null) ||
            (fd.getFile() == null))
            return;
        QTFile flatFile =
            new QTFile (new File (fd.getDirectory(),
                                  fd.getFile()));
        if (flatFile.exists()) {
            // JOptionPane is a bit of cheat-for-clarity here,
            // building a working AWT dialog would be punitive
            int choice = 
                JOptionPane.showConfirmDialog (this,
                              "Overwrite " + flatFile.getName() + "?",
                              "Flatten",
                              JOptionPane.OK_CANCEL_OPTION);
            if (choice != JOptionPane.OK_OPTION)
                return;
        }
        // flatten call has lots of flag options, see
        // http://developer.apple.com/documentation/QuickTime/APIREF/SOURCESI/flattenmovie.htm
        System.out.println ("Calling flatten()");
        movie.flatten(StdQTConstants.flattenAddMovieToDataFork |
                      StdQTConstants.flattenForceMovieResourceBeforeMovieData, // movieFlattenFlags
                      flatFile, // fileOut
                      StdQTConstants.kMoviePlayer, // creator
                      IOConstants.smSystemScript, // scriptTag
                      StdQTConstants.createMovieFileDeleteCurFile, // createQTFileFlags
                      StdQTConstants.movieInDataForkResID, // resID
                      null); // resName
        System.out.println ("Called flatten()");

    }



    public void doCopy() throws QTException {
        Movie copied = movie.copySelection();
        copied.putOnScrap(0);
        controller.movieChanged();
    }


    public void doCut() throws QTException {
        MovieEditState oldState = movie.newEditState();
        Movie cut = movie.cutSelection();
        MovieEditState newState = movie.newEditState();
        QTEdit edit = new QTEdit (oldState, newState, "Cut");
        undoManager.addEdit (edit);
        cut.putOnScrap(0);
        controller.movieChanged();
    }

    public void doPaste() throws QTException {
        MovieEditState oldState = movie.newEditState();
        Movie pasted = Movie.fromScrap(0);
        movie.pasteSelection (pasted);
        MovieEditState newState = movie.newEditState();
        QTEdit edit = new QTEdit (oldState, newState, "Paste");
        undoManager.addEdit (edit);
        controller.movieChanged();
        pack();
    }

    public void doUndo() throws QTException {
        if (! undoManager.canUndo()) {
            System.out.println ("can't undo");
            return;
        }
        System.out.println ("doUndo() - " +
                            undoManager.getUndoPresentationName());
        undoManager.undo();
    }

    public void doRedo() throws QTException {
        if (! undoManager.canRedo()) {
            System.out.println ("can't redo");
            return;
        }
        System.out.println ("doRedo() - " +
                            undoManager.getRedoPresentationName());
        undoManager.redo();
    }

    public void doAddAudioTrack() throws QTException {
        // ask for an audio file
        QTFile audioFile =
            QTFile.standardGetFilePreview (QTFile.kStandardQTFileTypes);
        OpenMovieFile omf = OpenMovieFile.asRead (audioFile);
        Movie audioMovie = Movie.fromFile (omf);
        // find the audio track, if any
        System.out.println (audioMovie.getTrackCount() + " tracks");
        Track audioTrack =
            audioMovie.getIndTrackType (1,
                                        StdQTConstants.audioMediaCharacteristic,
                                        StdQTConstants.movieTrackCharacteristic);
        if (audioTrack == null) {
            JOptionPane.showMessageDialog (this,
                                           "Didn't find audio track",
                                           "Error",
                                           JOptionPane.ERROR_MESSAGE);
            return;
        }
        // now make new audio track and insert segment
        // from the loaded track
        Track newTrack =
            movie.newTrack (0.0f, // width
                            0.0f, // height
                            audioTrack.getVolume());
        // ick, need a dataref for our "new" media
        // http://developer.apple.com/qa/qtmtb/qtmtb58.html
        SoundMedia newMedia =
            new SoundMedia (newTrack,
                            audioTrack.getMedia().getTimeScale(),
                            new DataRef (new QTHandle()));
        newTrack.getMedia().beginEdits();
        audioTrack.insertSegment (newTrack,
                                  0,
                                  audioTrack.getDuration(),
                                  0);
        controller.movieChanged();
        // this is throwing "-2045=dataAlreadyClosed"
        // newTrack.getMedia().endEdits();
    }

    /** Force frame's size to respect movie size
     */
    public Dimension getPreferredSize() {
        if (controller == null)
            return new Dimension (0,0);
        try {
            QDRect contRect = controller.getBounds();
            Dimension compDim = comp.getPreferredSize();
            if (contRect.getHeight() > compDim.height) {
                return new Dimension (contRect.getWidth() +
                                      getInsets().left +
                                      getInsets().right,
                                      contRect.getHeight() +
                                      getInsets().top +
                                      getInsets().bottom);

            } else {
                return new Dimension (compDim.width +
                                      getInsets().left +
                                      getInsets().right,
                                      compDim.height +
                                      getInsets().top +
                                      getInsets().bottom);

            }
        } catch (QTException qte) {
            return new Dimension (0,0);
        }
    }

    /** opens a single new movie window
     */
    public static void main (String[] args) {
        try {
            Frame f = makeNewAndShow();
            // note its x, y for future calls
            newFrameX = f.getLocation().x;
            newFrameY = f.getLocation().y;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /** creates "new" movie frame, packs and shows.
        used by main() and "new"
     */
    private static Frame makeNewAndShow()
        throws QTException {
        Frame f = new AddAudioTrackQTEditor();
        f.pack();
        if (newFrameX >= 0)
            f.setLocation (newFrameX+=16, newFrameY+=16);
        f.setVisible(true);
        windowCount++;
        return f;
    }

    class QTEdit extends AbstractUndoableEdit {
        MovieEditState previousState;
        MovieEditState newState;
        String name;
        public QTEdit (MovieEditState pState,
                       MovieEditState nState,
                       String n) {
            previousState = pState;
            newState = nState;
            this.name = n;
        }
        public String getPresentationName() {
            return name;
        }
        public void redo() throws CannotRedoException {
            super.redo();
            try {
                movie.useEditState (newState);
                controller.movieChanged();
            } catch (QTException qte) {
                qte.printStackTrace();
            }
        }
        public void undo () throws CannotUndoException {
            super.undo();
            try {
                movie.useEditState (previousState);
                controller.movieChanged();
            } catch (QTException qte) {
                qte.printStackTrace();
            }
        }
        public void die() {
            previousState = null;
            newState = null;
        }
    }

}