Implementation

For information about the design and functionality of the MIDlet, see section Design.

The MIDlet consists of a single class, AudioOutputControlMidlet.

To create the MIDlet:

  1. Create the AudioOutputControlMidlet.java class file. (In the IDE, create this class as a new MIDlet and delete any prefilled code.)

  2. Import the required classes.

    import javax.microedition.media.control.VideoControl;
    import javax.microedition.lcdui.*;
    import javax.microedition.media.*;
    import java.io.IOException;
    import com.nokia.mid.media.AudioOutputControl;
    import com.nokia.mid.media.AudioOutput;
    import javax.microedition.amms.GlobalManager;
    import javax.microedition.midlet.MIDlet;
  3. Set the AudioOutputControlMidlet class to extend MIDlet and implement CommandListener and PlayerListener. The MIDlet uses the CommandListener interface to handle playback, audio output control, and exit commands from the UI. The MIDlet uses the PlayerListener interface mainly to monitor for changes in the audio routing.

    public class AudioOutputControlMidlet extends MIDlet implements CommandListener, PlayerListener {
  4. Declare the commands and other global variables used by the MIDlet.

        private Form form;
        private StringItem audioOutputStr;
        // Commands
        private Command exitCommand;
        private Command clear;//Clear Form
        private Command play; // Start playing
        private Command pause;// Stop playing
        private Command close; // close the player instance
        private Command createMIDIPlayer; // Command to create MIDI player
        private Command createWavPlayer; // Command to create Wave player
        private Command createVideoPlayer; // Command to create video player
        // Commands to set audio output preference
        private Command setPreferencePublic;
        private Command setPreferencePrivate;
        private Command setPreferenceAll;
        private Command setPreferenceNone;
        private Command setPreferenceNoPreference;
        // Commands to get preferences
        private Command getPreference;
        private Command getCurrentPreference;
        // Command to get all supported preferences
        private Command getAllAvailablePreference;
        private Player player;
        private int i;
        private Item temp;
        private boolean videoPlayer = false, playerDeleted = false;
        public AudioOutputControl audioOutputControl;
  5. Implement the startApp method, which is run when the MIDlet starts. The method creates a new Form, which contains a StringItem, adds all the commands used by the MIDlet to the Form, and displays the Form on the device screen. The commands are created separately through custom methods (see step 8). The getHelloStringItem method creates the StringItem used by the Form.

        public void startApp() {
            form = new Form(null, new Item[]{getHelloStringItem()});
            form.addCommand(getExitCommand());
            form.addCommand(getCreateMIDICommand());
            form.addCommand(getCreateWavCommand());
            form.addCommand(getCreateVideoPlayerCommand());
            form.addCommand(getPlayCommand());
            form.addCommand(getPauseCommand());
            form.addCommand(getGetCurrentPreferenceCommand());
            form.addCommand(getGetPreferenceCommand());
            form.addCommand(getGetAllAvailablePreferenceCommand());
            form.addCommand(getSetPreferenceNoPreferenceCommand());
            form.addCommand(getSetPreferenceAllCommand());
            form.addCommand(getSetPreferenceNoneCommand());
            form.addCommand(getSetPreferencePrivateCommand());
            form.addCommand(getSetPreferencePublicCommand());
            form.addCommand(getCloseCommand());
            form.addCommand(getClearCommand());
            form.setCommandListener(this);
            getDisplay().setCurrent(form);
        }
    
        public StringItem getHelloStringItem() {
            if (audioOutputStr == null) {
                audioOutputStr = new StringItem(" Audio Output Control Example ", "");
            }
            return audioOutputStr;
        }
  6. Implement the commandAction method required for a CommandListener. This method is called every time a command event occurs in the Form, that is, every time the user selects a command from the MIDlet UI. The MIDlet uses the method to handle the corresponding action, for example starting playback or creating a new player.

    For each create<Player> command, the MIDlet creates a new Player of the appropriate type by calling the static Manager.createPlayer method, and retrieves an AudioOutputControl object for the Player by calling getControl on the Player and typecasting the returned Control object to an AudioOutputControl object. Based on the setPreference<Mode> command selected by the user in the MIDlet UI, the MIDlet uses the AudioOutputControl object, assigned to the global audioOutputControl variable, to set the audio output mode for the Player. Setting the audio output mode is handled separately in a custom method (see step 9).

        public void commandAction(Command command, Displayable displayable) {
            if (displayable == form) {
                if (command == exitCommand) {
                    exitMIDlet();
                }
    
                if (command == play) {
                    try {
                        if (playerDeleted == false) {
                            player.start();
                        } else if (playerDeleted == true) {
                            form.deleteAll();
                            i = form.append(temp);
                            player.start();
                        }
                    } catch (MediaException me) {
                    }
                }
    
                if (command == pause) {
                    try {
                        player.stop();
                    } catch (MediaException me) {
                    }
                }
    
                if (command == clear) {
                    player.close();
                    form.deleteAll();
                }
    
                if (command == close) {
                    player.close();
                }
    
                if (command == setPreferencePrivate) {
                    setAudioOutputPreferences(AudioOutputControl.PRIVATE);
                    form.append("\n Set To PRIVATE Mode");
                }
    
                if (command == setPreferencePublic) {
                    setAudioOutputPreferences(AudioOutputControl.PUBLIC);
                    form.append("\n Set To PUBLIC Mode");
                }
    
                if (command == setPreferenceAll) {
                    setAudioOutputPreferences(AudioOutputControl.ALL);
                    form.append("\n Set To ALL Mode");
                }
    
                if (command == setPreferenceNone) {
                    setAudioOutputPreferences(AudioOutputControl.NONE);
                    form.append("\n Set To None Mode");
                }
                if (command == setPreferenceNoPreference) {
                    setAudioOutputPreferences(AudioOutputControl.DEFAULT);
                    form.append("\n Set To Default Mode");
                }
    
                if (command == getPreference) {
                    try {
                        int preference = audioOutputControl.getOutputMode();
                        form.append("\nMode : " + preference);
                    } catch (Exception e) {
                        form.append("\ngetpreference Exception : " + e.toString());
                    }
                }
                if (command == getCurrentPreference) {
                    AudioOutput audioOutputObj = audioOutputControl.getCurrent();
                    form.append("\nCurrentMode : " + audioOutputObj.getActiveOutputMode());
                }
                if (command == getAllAvailablePreference) {
                    try {
                        int[] ret = audioOutputControl.getAvailableOutputModes();  //Setting up a variable to hold the return value from the method that tells us available output modes
                        form.append("Available audio output modes: \n");  //Showing the results to the user
                        for (int i = 0; i < ret.length; i++) //Gets each return value from the array
                        {
                            form.append(" ");
                            displayMode(ret[i]);
                        }
                    } catch (Exception e) {
                        form.append("\nException : " + e.toString());
                    }
                }
    
                if (command == createMIDIPlayer) {
                    try {
                        player = Manager.createPlayer(getClass().getResourceAsStream("/audio1.mid"), "audio/midi");
                        player.realize();
                        audioOutputControl = (AudioOutputControl) player.getControl("com.nokia.mid.media.AudioOutputControl");
                        if (audioOutputControl == null) {
                            audioOutputControl = (AudioOutputControl) GlobalManager.getControl("com.nokia.mid.media.AudioOutputControl");
                        }
                        if (audioOutputControl == null) {
                            form.append("\ncreateLocalPlayer : audioOutputControl not available");
                            return;
                        }
                        player.prefetch();
                        player.addPlayerListener(this);
                    } catch (IOException ioe) {
                        form.append("Getting IOException:" + ioe.toString());
                    } catch (MediaException me) {
                        form.append("Getting MediaException:" + me.toString());
                    } catch (Exception e) {
                        form.append("Getting OtherException:" + e.toString());
                    }
                }
    
                if (command == createVideoPlayer) {
                    try {
                        player = Manager.createPlayer(getClass().getResourceAsStream("/video1.3gp"), "video/3gp");
                        player.realize();
                        player.prefetch();
                        audioOutputControl = (AudioOutputControl) player.getControl("com.nokia.mid.media.AudioOutputControl");
                        if (audioOutputControl == null) {
                            audioOutputControl = (AudioOutputControl) GlobalManager.getControl("com.nokia.mid.media.AudioOutputControl");
                        }
                        temp = null;
                        VideoControl videoControl = (VideoControl) player.getControl("VideoControl");
                        temp = (Item) videoControl.initDisplayMode(VideoControl.USE_GUI_PRIMITIVE, null);
                        form.deleteAll();
                        i = form.append(temp);
                        videoPlayer = true;
                        if (audioOutputControl == null) {
                            form.append("\ncreateVideoPlayer : audioOutputControl not available");
                            return;
                        }
                        player.addPlayerListener(this);
                    } catch (IOException ioe) {
                        form.append("Getting IOException:" + ioe.toString());
                    } catch (MediaException me) {
                        form.append("Getting MediaException:" + me.toString());
                    } catch (Exception e) {
                        form.append("Getting OtherException:" + e.toString());
                    }
                }
    
                if (command == createWavPlayer) {
                    try {
                        player = Manager.createPlayer(getClass().getResourceAsStream("/audio2.wav"), "audio/wav");
                        player.realize();
                        audioOutputControl = (AudioOutputControl) player.getControl("com.nokia.mid.media.AudioOutputControl");
                        if (audioOutputControl == null) {
                            audioOutputControl = (AudioOutputControl) GlobalManager.getControl("com.nokia.mid.media.AudioOutputControl");
                        }
                        if (audioOutputControl == null) {
                            form.append("\ncreateWavPlayer : audioOutputControl not available");
                            return;
                        }
                        player.prefetch();
                        player.addPlayerListener(this);
                    } catch (IOException ioe) {
                        form.append("Getting IOException:" + ioe.toString());
                    } catch (MediaException me) {
                        form.append("Getting MediaException:" + me.toString());
                    } catch (Exception e) {
                        form.append("Getting OtherException:" + e.toString());
                    }
                }
            }
        }

    In addition, implement the custom displayMode method used in handling the getAllAvailablePreference command.

        private void displayMode(int mode) {
            switch (mode) {
                case AudioOutputControl.DEFAULT:
                    form.append("DEFAULT: " + mode + "\n");
                    break;
                case AudioOutputControl.ALL:
                    form.append("ALL:" + mode + "\n");
                    break;
                case AudioOutputControl.NONE:
                    form.append("NONE:" + mode + "\n");
                    break;
                case AudioOutputControl.PRIVATE:
                    form.append("PRIVATE: " + mode + "\n");
                    break;
                case AudioOutputControl.PUBLIC:
                    form.append("PUBLIC: " + mode + "\n");
                    break;
                default:
                    form.append("Unexpected return: " + mode + "\n");
            }
        }
  7. Implement methods for providing the Display object used by the MIDlet and for gracefully exiting the MIDlet.

        public Display getDisplay() {
            return Display.getDisplay(this);
        }
    
        public void exitMIDlet() {
            getDisplay().setCurrent(null);
            destroyApp(true);
            notifyDestroyed();
        }
  8. Create the Commands used by the MIDlet. Each Command is created in its own method. The startApp method uses these methods when adding the Commands to the Form.

        public Command getExitCommand() {
            if (exitCommand == null) {
                exitCommand = new Command("Exit", Command.EXIT, 1);
            }
            return exitCommand;
        }
    
        public Command getCreateMIDICommand() {
            if (createMIDIPlayer == null) {
                createMIDIPlayer = new Command("Create audio player (MIDI)", Command.ITEM, 2);
            }
            return createMIDIPlayer;
        }
    
        public Command getCreateWavCommand() {
            if (createWavPlayer == null) {
                createWavPlayer = new Command("Create audio player (WAV)", Command.ITEM, 3);
            }
            return createWavPlayer;
    
        }
    
        public Command getCreateVideoPlayerCommand() {
            if (createVideoPlayer == null) {
                createVideoPlayer = new Command("Create video player (3GP)", Command.ITEM, 4);
            }
            return createVideoPlayer;
        }
    
        public Command getPlayCommand() {
            if (play == null) {
                play = new Command("Start playback", Command.ITEM, 5);
            }
            return play;
        }
    
        public Command getPauseCommand() {
            if (pause == null) {
                pause = new Command("Stop playback", Command.ITEM, 6);
            }
            return pause;
        }
    
        public Command getGetCurrentPreferenceCommand() {
            if (getCurrentPreference == null) {
                getCurrentPreference = new Command("Get active mode", Command.ITEM, 7);
            }
            return getCurrentPreference;
        }
    
        public Command getGetPreferenceCommand() {
            if (getPreference == null) {
                getPreference = new Command("Get mode", Command.ITEM, 8);
            }
            return getPreference;
        }
    
        public Command getGetAllAvailablePreferenceCommand() {
            if (getAllAvailablePreference == null) {
                getAllAvailablePreference = new Command("Get supported modes", Command.ITEM, 9);
            }
            return getAllAvailablePreference;
        }
    
        public Command getSetPreferenceNoPreferenceCommand() {
            if (setPreferenceNoPreference == null) {
                setPreferenceNoPreference = new Command("Set mode DEFAULT", Command.ITEM, 10);
            }
            return setPreferenceNoPreference;
        }
    
        public Command getSetPreferenceAllCommand() {
            if (setPreferenceAll == null) {
                setPreferenceAll = new Command("Set mode ALL", Command.ITEM, 11);
            }
            return setPreferenceAll;
        }
    
        public Command getSetPreferenceNoneCommand() {
            if (setPreferenceNone == null) {
                setPreferenceNone = new Command("Set mode NONE", Command.ITEM, 12);
            }
            return setPreferenceNone;
        }
    
        public Command getSetPreferencePrivateCommand() {
            if (setPreferencePrivate == null) {
                setPreferencePrivate = new Command("Set mode PRIVATE", Command.ITEM, 13);
            }
            return setPreferencePrivate;
        }
    
        public Command getSetPreferencePublicCommand() {
            if (setPreferencePublic == null) {
                setPreferencePublic = new Command("Set mode PUBLIC", Command.ITEM, 14);
            }
            return setPreferencePublic;
        }
    
        public Command getCloseCommand() {
            if (close == null) {
                close = new Command("Close player", Command.ITEM, 15);
            }
            return close;
        }
    
        public Command getClearCommand() {
            if (clear == null) {
                clear = new Command("Clear Form", Command.ITEM, 16);
            }
            return clear;
        }
  9. Implement the method for setting the audio output mode for a Player. The method calls the setOutputMode method on the AudioOutputControl object created for the Player.

        public void setAudioOutputPreferences(int mode) {
            audioOutputControl.setOutputMode(mode);
        }
  10. Add the remaining mandatory MIDlet lifecycle methods.

        public void pauseApp() {
        }
    
        public void destroyApp(boolean unconditional) {
            setAudioOutputPreferences(AudioOutputControl.DEFAULT);
        }
  11. Implement the playerUpdate method required for a PlayerListener. This method is called every time a Player event occurs. The MIDlet uses the method to update the UI when the audio output mode is changed (com.nokia.audiooutputchange.event) and when a playing Player has reached the end of its media (PlayerListener.END_OF_MEDIA).

        public void playerUpdate(Player aPlayer, String aEvent, Object aEventData) {
            if (aEvent.equals("com.nokia.audiooutputchange.event")) {
                int k = ((AudioOutput) aEventData).getActiveOutputMode();
                switch (k) {
                    case 0:
                        form.append("\nAudioOutputModeChangedTo: DEFAULT");
                        break;
                    case 1:
                        form.append("\nAudioOutputModeChangedTo: ALL");
                        break;
                    case 2:
                        form.append("\nAudioOutputModeChangedTo: NONE");
                        break;
                    case 3:
                        form.append("\nAudioOutputModeChangedTo: PRIVATE");
                        break;
                    case 4:
                        form.append("\nAudioOutputModeChangedTo: PUBLIC");
                        break;
                    default:
                        form.append("Unexpected return:");
                }
            }
            if (aEvent.equals(PlayerListener.END_OF_MEDIA) && videoPlayer == true) {
                form.delete(i);
                playerDeleted = true;
            }
        }
    }