package com.ociweb.midp2;

import java.io.IOException;

import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Form;
import javax.microedition.media.Manager;
import javax.microedition.media.MediaException;
import javax.microedition.media.Player;
import javax.microedition.media.PlayerListener;
import javax.microedition.media.control.ToneControl;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;

public class PlayToneSequenceMIDlet extends MIDlet implements PlayerListener {
    private byte TEMPO = 30;
    private byte volume = 100;
    private byte d = 8; // eighth note
    
    private byte C = ToneControl.C4;
    private byte D = (byte) (C + 2); // a whole step
    private byte E = (byte) (C + 4); // a major third


    private Player p;
    private ToneControl c;
    private Form form = new Form("Now Playing");
    
    protected void startApp() throws MIDletStateChangeException {
        Display.getDisplay(this).setCurrent(form);
        try {
            play();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (MediaException e) {
            e.printStackTrace();
        }
    }
    
    private void play() throws IOException, MediaException {
        form.append("Quiet!");
        p = Manager.createPlayer(Manager.TONE_DEVICE_LOCATOR);
        p.addPlayerListener(this);
        p.realize();
        c = (ToneControl) p.getControl("ToneControl");
        c.setSequence(createSequence());
        p.start();
    }
    private byte[] createSequence() {
        byte[] sequence = { 
                ToneControl.VERSION, 1, // version 1
                ToneControl.TEMPO, TEMPO, // set tempo
                ToneControl.SET_VOLUME, volume,
                ToneControl.BLOCK_START, 0, // Define block 0
                    C, d, D, d, E, d, // Define repeatable block of 3 eighth notes
                ToneControl.BLOCK_END, 0, // End block 0
                ToneControl.PLAY_BLOCK, 0, // play block 0
                ToneControl.SILENCE, d, E, d, D, d, C, d, // play some other notes
                ToneControl.PLAY_BLOCK, 0, // play block 0 again
            };
        return sequence;
    }
    public void playerUpdate(Player player, String event, Object eventData) {
        if (event == PlayerListener.END_OF_MEDIA && volume > 10) {
            p.close(); // release the resources
            try {
                volume /= 2;
                play();
            } catch (IOException e1) {
                e1.printStackTrace();
            } catch (MediaException e) {
                e.printStackTrace();
            }
        } else if (volume < 10) {
            p.close();
            notifyDestroyed();
        }
    }
    protected void pauseApp() {}

    protected void destroyApp(boolean unconditional)
            throws MIDletStateChangeException {}
}
