To finish this chapter, we’ll look at a very simple example of QTJ code that actually plays some media. To keep things simple, I’ll completely ignore the GUI, so all this will do is take a file path from the command line—presumably an MP3 or other audio file—and play it in QTJ.
Compile and run the source for TrivialAudioPlayer.java, shown in Example 1-5.
Example 1-5. Playing an audio file from the command line
package com.oreilly.qtjnotebook.ch01; import quicktime.*; import quicktime.app.time.*; import quicktime.io.*; import quicktime.std.*; import quicktime.std.movies.*; import java.io.*; public class TrivialAudioPlayer { public static void main (String[ ] args) { if (args.length != 1) { System.out.println ( "Usage: TrivialAudioPlayer <file>"); return; } try { QTSessionCheck.check( ); QTFile f = new QTFile (new File(args[0])); OpenMovieFile omf = OpenMovieFile.asRead(f); Movie movie = Movie.fromFile (omf); TaskAllMovies.addMovieAndStart( ); movie.start( ); } catch (QTException e) { e.printStackTrace( ); } } }
Once compiled, run it with the path to an audio file as a
command-line argument. Note that if you downloaded the book examples
and compiled with the ant
buildfile, the classes
will be in the classes
directory, so
you’ll need to extend your classpath into there:
cadamson% java -classpath classes com.oreilly.qtjnotebook.ch01.TrivialAudioPlayer ~/mp3testing/Breakaway.mp3
This application provides a bare-bones load-and-play example. After
checking that there’s a valid argument, it does the
QTSessionCheck
from the previous task to set up
the QuickTime session.
Note
Any dynamic content in QuickTime is going to be a “movie,” even if it’s an audio-only file, like an MP3. This program also works for AACs, WAVs, iTunes Music Store songs, and anything else QuickTime can open.
The interesting part is in converting the argument to a
java.io.File
, then to a
quicktime.io.OpenMovieFile
, from which we can
create a quicktime.std.Movie
, which represents any
kind of playable QuickTime content, in this case our audio file.
The start( )
method begins playing the movie, so
once the program is running, you’ll hear your MP3
over your speakers or headphones. This program
doesn’t provide a way to stop playback, so when you
want to end the program, you’ll need to type
ctrl-c
, use the Windows Task Manager, or hit
the Quit menu item that’s provided on Mac OS X.
...that weird TaskAllMovies
call? This is required
because our program doesn’t have a GUI, which
ordinarily gives QTJ some cycles for decoding and playing the audio.
Most of the programs in this book have on-screen GUIs, so they
don’t need to do this.
Get QuickTime for Java: A Developer's Notebook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.