Wednesday, January 9, 2013

BlackBerry Playing audio from a web URL

Make a new project with name AudioPlaybackDemoScreen and copy the following code to AudioPlaybackDemoScreen.java


package audioplaying;

import net.rim.device.api.command.Command;
import net.rim.device.api.command.CommandHandler;
import net.rim.device.api.command.ReadOnlyCommandMetadata;
import net.rim.device.api.ui.*;
import net.rim.device.api.ui.container.*;
import net.rim.device.api.ui.component.*;

import javax.microedition.media.*;
import javax.microedition.media.control.*;
import java.io.*;

public class AudioPlaybackDemoScreen extends MainScreen implements
FieldChangeListener

{
Player p;
ButtonField audio;
private VerticalFieldManager vfm = new VerticalFieldManager();

public AudioPlaybackDemoScreen() {
audio = new ButtonField("Strat");

add(audio);

ButtonField playButton = new ButtonField("Play",
ButtonField.CONSUME_CLICK | ButtonField.NEVER_DIRTY);
playButton.setCommand(new Command(new CommandHandler() {
public void execute(ReadOnlyCommandMetadata metadata,
Object object) {
// Start the video
try {
p.start();
p.setLoopCount(-1);
} catch (Exception e) {
Dialog.inform(e.getMessage());
}
}
}));
add(playButton);

ButtonField pauseButton = new ButtonField("Pause",
ButtonField.CONSUME_CLICK | ButtonField.NEVER_DIRTY);
pauseButton.setCommand(new Command(new CommandHandler() {
public void execute(ReadOnlyCommandMetadata metadata,
Object object) {
// Pause the video
try {
if(p!=null){
p.stop();}else{Dialog.inform("Press start");}
} catch (Exception e) {
Dialog.inform(e.getMessage());
}
}
}));
add(pauseButton);
ButtonField closeButton = new ButtonField("Stop",
ButtonField.CONSUME_CLICK | ButtonField.NEVER_DIRTY);
closeButton.setCommand(new Command(new CommandHandler() {
public void execute(ReadOnlyCommandMetadata metadata,
Object object) {
// Pause the video
try {
if(p!=null){
p.stop();
p.close();}else{Dialog.inform("Press start");}
} catch (Exception e) {
Dialog.inform(e.getMessage());
}
}
}));
add(closeButton);
audio.setChangeListener(this);

}

public void fieldChanged(Field field, int context) {
// TODO Auto-generated method stub
if (audio == field) {

try {
p = javax.microedition.media.Manager
.createPlayer("http://www.virginmegastore.me/Library/Music/CD_001214/Tracks/Track1.mp3"
+ ";deviceside=true");
p.realize();
VolumeControl volume = (VolumeControl) p
.getControl("VolumeControl");
volume.setLevel(30);
p.setLoopCount(-1);
p.prefetch();
p.start();

} catch (MediaException me) {
Dialog.alert(me.toString());
} catch (IOException ioe) {
Dialog.alert(ioe.toString());
}
}
}
}

just run and use the buttons on the screens. :) enhance the code accordingly for yours need!!

No comments:

Post a Comment