/* 
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/

import com.antelmann.sound.SoundPlayer;
import com.antelmann.sound.SoundException;
import com.antelmann.util.Misc;
import com.antelmann.util.StopWatch;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;

/**
* @author Holger Antelmann
*/
class Play
{
    /**
    * plays a media file
    */
    public static void main (String[] args) {
        if (args.length < 1) {
            System.out.println("usage: \"java Play <filename | URL>\"");
            return;
        }
        final SoundPlayer player = getPlayer(args[0]);
        if (player == null) {
            System.out.println("cannot play given source");
            System.exit(1);
        }
        System.out.println("sound type: " + player.getSoundTypeDescription());
        System.out.println("length: " + new StopWatch(player.getMicrosecondLength() / 1000).display());
        System.out.println("starting playback (printing a dot after every 5 seconds)");
        player.play();
        int count = 0;
        Thread.currentThread().yield(); // important so that the player plays before the next call
        while (player.isPlaying()) {
            Misc.pause(500);
            if ((++count % 10) == 0) System.out.print(".");
        }
        player.close();
        System.out.println("\ndone");
        System.exit(0);
    }


    static SoundPlayer getPlayer(String sound) {
        SoundPlayer player = null;
        try {
            // if you have the MP3 libraries, you can also
            // use an MP3Player instance here
            player = new SoundPlayer(new URL(sound));
        } catch (SoundException ex) {
            return null;
        } catch (MalformedURLException e) {
            try {
            // if you have the MP3 libraries, you can also
            // use an MP3Player instance here
                player = new SoundPlayer(new File(sound));
            } catch (SoundException ex) {
                return null;
            }
        }
        return player;
    }
}