/*
 *  BasicSoundtrack.java
 *  Cookbook
 *
 *  Copyright (c) 2001-2009 Flagstone Software Ltd. All rights reserved.
 *
 *  This code is distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, 
 *  EITHER EXPRESS OR IMPLIED, AND Flagstone HEREBY DISCLAIMS ALL SUCH WARRANTIES, 
 *  INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR 
 *  A PARTICULAR PURPOSE, AND NONINFRINGEMENT OF THIRD PARTY RIGHTS.
 */

import com.flagstone.transform.*;
import com.flagstone.transform.util.*;

import java.io.IOException;
import java.util.zip.DataFormatException;

/*
 * This example shows how the FSSoundConstructor class can be used to generate
 * the objects used to play streaming sounds in a movie.
 *
 * For an example of how to play a sound in response to a button being clicked see
 * the Buttons example.
 *
 * To run this example, type the following on a command line:
 *
 *     java -cp cookbook.jar BasicSoundtrack sound-file file-out
 *
 * where
 *
 *     sound-file is the path to a file containing a WAVE or MP3 format sound.
 *
 *     file-out is the path where the file will be written. If no output file 
 *     is specified then a file named after the example will be written to the 
 *     current directory.
 */
public class BasicSoundtrack
{
    public static void main(String[] args)
    {
        try
        {
        	String out = args.length == 1 ? "BasicSoundtrack.swf" : args[1];
        	BasicSoundtrack example = new BasicSoundtrack();         
            FSMovie movie = new FSMovie();            
            example.createMovie(movie, args[0]);
            movie.encodeToFile(out);
        }
        catch (Exception e)
        {
        	e.printStackTrace();
        }
    }
    
    void createMovie(FSMovie movie, String soundFile) throws DataFormatException, IOException
    {
        float framesPerSecond = 12.0f;
        FSSoundConstructor soundGenerator = new FSSoundConstructor(soundFile);

        /*
         * Calculate the number of decoded sound samples played for each frame and
         * the size, in bytes, of each block compressed sound data.
         */
        int samplesPerBlock = soundGenerator.getSampleRate() / (int) framesPerSecond;
        int numberOfBlocks = soundGenerator.getSamplesPerChannel() / samplesPerBlock;

		/* 
		 * Add all the objects together to create the movie.
		 */
		movie.setFrameSize(new FSBounds(0, 0, 8000, 4000));
		movie.setFrameRate(framesPerSecond);
		movie.add(new FSSetBackgroundColor(FSColorTable.lightblue()));

        /* 
         * An FSSoundStreamHeader2 object defines the attributes of the streaming sound.
		 */
        movie.add(soundGenerator.streamHeader(samplesPerBlock));

        /* 
         * Add a streaming block for each frame so the sound is played as each frame 
         * is displayed.
         */
        for (int i=0; i