Java Tutorial/J2ME/Audio Player

Материал из Java эксперт
Перейти к: навигация, поиск

Audio Player Demo

import javax.microedition.lcdui.rumand;
import javax.microedition.lcdui.rumandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.Gauge;
import javax.microedition.lcdui.Item;
import javax.microedition.lcdui.ItemStateListener;
import javax.microedition.lcdui.List;
import javax.microedition.media.Manager;
import javax.microedition.media.Player;
import javax.microedition.media.control.VolumeControl;
import javax.microedition.midlet.MIDlet;
class AudioPlayerCanvas implements ItemStateListener {
  private AudioPlayer parent;
  private Form form = new Form("");
  private Gauge gauge = new Gauge("Volume: 50", true, 100, 50);
  private VolumeControl volume;
  private Player player;
  private boolean paused = false;
  public AudioPlayerCanvas(AudioPlayer parent) {
    this.parent = parent;
    form.append(gauge);
    form.addCommand(parent.exitCommand);
    form.addCommand(parent.backCommand);
    form.setCommandListener(parent);
    form.setItemStateListener(this);
  }
  public void playMedia(String locator) {
    try {
      player = Manager.createPlayer(getClass().getResourceAsStream(locator), "audio/x-wav");
      player.realize();
      volume = (VolumeControl) player.getControl("VolumeControl");
      volume.setLevel(50);
      gauge.setValue(volume.getLevel());
      gauge.setLabel("Volume: " + volume.getLevel());
      player.setLoopCount(2);
      player.start();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  public void pauseMedia() {
    if (player != null) {
      try {
        player.stop();
        paused = true;
      } catch (Exception e) {
      }
    }
  }
  public void restartMedia() {
    if (player != null) {
      try {
        player.start();
        paused = false;
      } catch (Exception e) {
      }
    }
  }
  public boolean isPlayerPaused() {
    return paused;
  }
  public Form getForm() {
    return this.form;
  }
  public void itemStateChanged(Item item) {
    volume.setLevel(gauge.getValue());
    gauge.setLabel("Volume: " + volume.getLevel());
  }
  public void cleanUp() {
    if (player != null) {
      player.close();
      player = null;
    }
  }
}
public class J2MEAudioPlayer extends MIDlet implements CommandListener {
  private String[] audioDisplayList = { "y.wav", "e.wav", "r.wav" };
  private String[] audioList = { "/y.wav", "/e.wav", "/r.wav" };
  protected Display display;
  private AudioPlayerCanvas canvas;
  private List list = new List("Pick an Audio file", List.IMPLICIT, audioDisplayList, null);
  protected Command exitCommand = new Command("Exit", Command.EXIT, 1);
  protected Command backCommand= new Command("Back", Command.BACK, 1);
  public J2MEAudioPlayer() {
    list.addCommand(exitCommand);
    list.setCommandListener(this);
    canvas = new AudioPlayerCanvas(this);
    display = Display.getDisplay(this);
  }
  public void startApp() {
    if (canvas.isPlayerPaused()) {
      canvas.restartMedia();
      display.setCurrent(canvas.getForm());
    } else {
      display.setCurrent(list);
    }
  }
  public void pauseApp() {
    canvas.pauseMedia();
  }
  public void destroyApp(boolean unconditional) {
    canvas.cleanUp();
  }
  public void commandAction(Command command, Displayable disp) {
    if (command == exitCommand) {
      canvas.cleanUp(); 
      notifyDestroyed();
      return;
    } else if (command == backCommand) { 
      canvas.cleanUp();
      display.setCurrent(list);
      return;
    }
    if (disp == list) {
      canvas.playMedia(audioList[list.getSelectedIndex()]);
      display.setCurrent(canvas.getForm());
    }
  }
}





Cached Audio Player

import java.util.Enumeration;
import java.util.Hashtable;
import javax.microedition.lcdui.rumand;
import javax.microedition.lcdui.rumandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.Gauge;
import javax.microedition.lcdui.Item;
import javax.microedition.lcdui.ItemStateListener;
import javax.microedition.lcdui.List;
import javax.microedition.media.Manager;
import javax.microedition.media.Player;
import javax.microedition.media.control.VolumeControl;
import javax.microedition.midlet.MIDlet;
class CachedAudioPlayerCanvas implements ItemStateListener {
  private CachingAudioPlayer parent;
  private Form form = new Form("");
  private Gauge gauge = new Gauge("Volume: 50", true, 100, 50);
  private VolumeControl volume;
  private Player player;
  private boolean paused = false;
  private Hashtable players = new Hashtable();
  public CachedAudioPlayerCanvas(CachingAudioPlayer parent) {
    this.parent = parent;
    form.append(gauge);
    form.addCommand(parent.exitCommand);
    form.addCommand(parent.backCommand);
    form.setCommandListener(parent);
    form.setItemStateListener(this);
  }
  public void playMedia(String locator) {
    try {
      player = (Player) players.get(locator);
      if (player == null) {
        player = Manager.createPlayer(getClass().getResourceAsStream(locator), "audio/x-wav");
        player.prefetch();
        players.put(locator, player);
      }
      volume = (VolumeControl) player.getControl("VolumeControl");
      volume.setLevel(50);
      gauge.setValue(volume.getLevel());
      gauge.setLabel("Volume: " + volume.getLevel());
      player.setLoopCount(2);
      player.start();
      form.setTitle("Playing " + locator);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  public void pauseMedia() {
    if (player != null) {
      try {
        player.stop();
        paused = true;
      } catch (Exception e) {
      }
    }
  }
  public void restartMedia() {
    if (player != null) {
      try {
        player.start();
        paused = false;
      } catch (Exception e) {
      }
    }
  }
  public boolean isPlayerPaused() {
    return paused;
  }
  public Form getForm() {
    return this.form;
  }
  public void itemStateChanged(Item item) {
    volume.setLevel(gauge.getValue());
    gauge.setLabel("Volume: " + volume.getLevel());
  }
  public void cleanUp() {
    if (player != null) {
      try {
        player.setMediaTime(0);
      } catch (Exception e) {
      }
      player.deallocate();
      player = null;
    }
  }
  public void closeAll() {
    for (Enumeration e = players.elements(); e.hasMoreElements();) {
      Player p = (Player) e.nextElement();
      p.close();
    }
  }
}
public class J2MECachingAudioPlayer extends MIDlet implements CommandListener {
  private String[] audioDisplayList = { "B", "A", "L" };
  private String[] audioList = { "/b.wav", "/a.wav", "/l.wav" };
  protected Display display;
  private CachedAudioPlayerCanvas canvas;
  private List list = new List("Pick an Audio file", List.IMPLICIT, audioDisplayList, null);
  protected Command exitCommand = new Command("Exit", Command.EXIT, 1);
  protected Command backCommand = new Command("Back", Command.BACK, 1);
  public J2MECachingAudioPlayer() {
    list.addCommand(exitCommand);
    list.setCommandListener(this);
    canvas = new CachedAudioPlayerCanvas(this);
    display = Display.getDisplay(this);
  }
  public void startApp() {
    if (canvas.isPlayerPaused()) {
      canvas.restartMedia();
      display.setCurrent(canvas.getForm());
    } else {
      display.setCurrent(list);
    }
  }
  public void pauseApp() {
    canvas.pauseMedia();
  }
  public void destroyApp(boolean unconditional) {
    canvas.closeAll();
  }
  public void commandAction(Command command, Displayable disp) {
    if (command == exitCommand) {
      canvas.closeAll(); 
      notifyDestroyed(); 
      return;
    } else if (command == backCommand) {
      canvas.cleanUp();
      display.setCurrent(list);
      return;
    }
  }
}





implements PlayerListener

import javax.microedition.lcdui.StringItem;
import javax.microedition.media.Player;
import javax.microedition.media.PlayerListener;
import javax.microedition.media.control.VolumeControl;
public class EventHandler implements PlayerListener {
  private StringItem item;
  public EventHandler(StringItem item) {
    this.item = item;
  }
  public void playerUpdate(Player player, String event, Object eventData) {
    if (event == (PlayerListener.VOLUME_CHANGED)) {
      VolumeControl vc = (VolumeControl) eventData;
      updateDisplay("Volume Changed to: " + vc.getLevel());
      if (vc.getLevel() > 60) {
        updateDisplay("Volume higher than 60 is too loud");
        vc.setLevel(60);
      }
    } else if (event == (PlayerListener.STOPPED)) {
      updateDisplay("Player paused at: " + (Long) eventData);
    } else if (event == (PlayerListener.STARTED)) {
      updateDisplay("Player started at: " + (Long) eventData);
    } else if (event == (PlayerListener.END_OF_MEDIA)) {
      updateDisplay("Player reached end of loop.");
    } else if (event == (PlayerListener.CLOSED)) {
      updateDisplay("Player closed.");
    } else if (event == (PlayerListener.ERROR)) {
      updateDisplay("Error Message: " + (String) eventData);
    }
  }
  public void updateDisplay(String text) {
    item.setText(text);
    System.err.println(text);
  }
}





Load WAV file from a web site

import javax.microedition.lcdui.rumand;
import javax.microedition.lcdui.rumandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.List;
import javax.microedition.lcdui.StringItem;
import javax.microedition.media.Manager;
import javax.microedition.media.Player;
import javax.microedition.midlet.MIDlet;
public class J2MENetworkTest extends MIDlet implements CommandListener {
  private List list = new List("Press Play", List.IMPLICIT);
  private Display display;
  public J2MENetworkTest() {
    list.addCommand(new Command("Exit", Command.EXIT, 1));
    list.addCommand(new Command("Play", Command.SCREEN, 1));
    list.setCommandListener(this);
    display = Display.getDisplay(this);
  }
  public void startApp() {
    display.setCurrent(list);
  }
  public void pauseApp() {
  }
  public void destroyApp(boolean unconditional) {
  }
  public void commandAction(Command cmd, Displayable disp) {
    if (cmd.getLabel().equals("Exit")) {
      notifyDestroyed();
    } else {
      try {
        Player player = Manager.createPlayer("http://www.yoursite.ru/s.wav");
        player.start();
      } catch (Exception e) {
        System.err.println(e);
      }
    }
  }
}





Network Player Manager

import javax.microedition.lcdui.rumand;
import javax.microedition.lcdui.rumandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.List;
import javax.microedition.lcdui.StringItem;
import javax.microedition.media.Manager;
import javax.microedition.media.Player;
import javax.microedition.midlet.MIDlet;
class ThreadedMIDlet extends MIDlet implements CommandListener {
  private List list = new List("Press Play", List.IMPLICIT);
  private Display display;
  private NetworkPlayerManager mgr;
  private Command cancel = new Command("Cancel", Command.CANCEL, 1);
  public ThreadedMIDlet() {
    list.addCommand(new Command("Exit", Command.EXIT, 1));
    list.addCommand(new Command("Play", Command.SCREEN, 1));
    list.setCommandListener(this);
    display = Display.getDisplay(this);
  }
  public void startApp() {
    display.setCurrent(list);
  }
  public void pauseApp() {
  }
  public void destroyApp(boolean unconditional) {
  }
  public void commandAction(Command cmd, Displayable disp) {
    if (cmd.getLabel().equals("Exit")) {
      notifyDestroyed();
    } else if (cmd.getLabel().equals("Cancel")) {
      mgr.cancel();
      display.setCurrent(list);
    } else {
      try {
        mgr = new NetworkPlayerManager(display, cancel, this);
        Thread runner = new Thread(mgr);
        runner.start();
      } catch (Exception e) {
        System.err.println(e);
      }
    }
  }
}
public class NetworkPlayerManager implements Runnable {
  private Display display;
  private Form form = new Form("Network Player Manager");
  private StringItem msg = new StringItem("Please Wait ... ", null);
  private boolean cancel = false;
  private Player player = null;
  public NetworkPlayerManager(Display display, Command cancelCmd, ThreadedMIDlet parent) {
    this.display = display;
    form.append(msg);
    form.addCommand(cancelCmd);
    form.setCommandListener(parent);
  }
  public void run() {
    display.setCurrent(form);
    boolean connected = false;
    try {
      player = Manager.createPlayer("http://www.yoursite.ru/s.wav");
      player.realize();
      connected = true;
    } catch (Exception e) {
      msg.setText("Failed: " + e.getMessage());
      System.err.println(e);
      return;
    }
    if (connected && !cancel)
      msg.setText("Connected. Starting playback...");
    else {
      msg.setText("Unable to connect.");
      return;
    }
    try {
      player.start();
    } catch (Exception pe) {
      msg.setText(pe.getMessage());
    }
  }
  public void cancel() {
    cancel = true;
    if (player != null)
      player.deallocate();
  }
}





Player Event

import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.StringItem;
import javax.microedition.media.Manager;
import javax.microedition.media.Player;
import javax.microedition.media.PlayerListener;
import javax.microedition.midlet.MIDlet;
public class EchoEventsMIDlet extends MIDlet implements PlayerListener {
  private StringItem stringItem = new StringItem("", null);
  public void startApp() {
    try {
      Form form = new Form("Player State");
      form.append(stringItem);
      Display.getDisplay(this).setCurrent(form);
      Player player = Manager.createPlayer(getClass().getResourceAsStream("/b.wav"), "audio/x-wav");
      player.addPlayerListener(this);
      player.start();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  public void pauseApp() {
  }
  public void destroyApp(boolean unconditional) {
  }
  public void playerUpdate(Player player, String event, Object eventData) {
    stringItem.setText(event);
    System.err.println(event);
  }
}





Wav file player

import javax.microedition.media.Manager;
import javax.microedition.media.Player;
import javax.microedition.midlet.MIDlet;
public class J2MESimplePlayer extends MIDlet {
  public void startApp() {
    try {
      Player player = Manager.createPlayer(getClass().getResourceAsStream("/b.wav"), "audio/x-wav");
      player.start();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  public void pauseApp() {
  }
  public void destroyApp(boolean unconditional) {
  }
}