How to continuous play audio files in Blackberry? - blackberry

I wanted to create a Blackberry application that plays a few audio files continuous one after another. But the application I created can open all the audio files continuously but did not managed to play the whole audio files. Can anyone know a solution for this? Below is my codes:
package mypackage;
import javax.microedition.media.Manager;
import javax.microedition.media.MediaException;
import javax.microedition.media.Player;
import java.lang.Class;
import javax.microedition.rms.RecordStore;
import java.io.InputStream;
import java.io.ByteArrayInputStream;
import net.rim.device.api.media.protocol.ByteArrayInputStreamDataSource;
import net.rim.device.api.system.*;
import net.rim.device.api.ui.*;
import net.rim.device.api.ui.component.*;
import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.ui.extension.container.*;
import net.rim.device.api.ui.UiApplication;
import java.io.IOException;
public class PlayMedia extends UiApplication{
/**
* Entry point for application
* #param args Command line arguments (not used)
*/
public static void main(String[] args){
PlayMedia theApp = new PlayMedia();
theApp.enterEventDispatcher();
}
public PlayMedia()
{
pushScreen(new PlayMediaScreen());
}
/**
* A class extending the MainScreen class, which provides default standard
* behavior for BlackBerry GUI applications.
*/
final class PlayMediaScreen extends MainScreen
{
/**
* Creates a new PlayMediaScreen object
*/
PlayMediaScreen()
{
String test1 = "Test(2seconds).mp3";
String test2 = "Test(2seconds)2.mp3";
String test3 = "Test(2seconds)3.mp3";
String test4 = "Test(2seconds)4.mp3";
String test5 = "blind_willie.mp3";
String mp3 = null;
for(int i=0;i<5;i++){
if(i == 0){
mp3 = test1;
}
else if(i == 1){
mp3 = test2;
}
else if(i == 2){
mp3 = test3;
}
else if(i == 3){
mp3 = test4;
}
else if(i == 4){
mp3 = test5;
}
play(mp3);
}
}
private void play(String mp3){
Player p = null;
InputStream stream = (InputStream)this.getClass().getResourceAsStream("/" + mp3);
try {
//p = Manager.createPlayer(source);
p = Manager.createPlayer(stream, "audio/mpeg");
p.realize();
p.prefetch();
//testing
System.out.println("Creating Players!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
System.out.println("The mp3 is " + mp3 + "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
//testing
System.out.println("IO Exeception!!!!!!!!!!!!!!!!1 " + e);
//testing
System.out.println(p);
} catch (MediaException e) {
// TODO Auto-generated catch block
e.printStackTrace();
//testing
System.out.println("Media Exeception!!!!!!!!!!!!!!!!1" + e);
//testing
System.out.println(p);
}
/*
* Best practice is to invoke realize(), then prefetch(), then start().
* Following this sequence reduces delays in starting media playback.
*
* Invoking start() as shown below will cause start() to invoke prefetch(0),
* which invokes realize() before media playback is started.
*/
try {
p.start();
} catch (MediaException e) {
// TODO Auto-generated catch block
e.printStackTrace();
//testing
System.out.println("Media Exeception for starting!!!!!!!!!!!!!!!!1" + e);
//testing
System.out.println(p);
}
try {
p.stop();
} catch (MediaException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
p.deallocate();
p.close();
}
}
}

You can save the files that you want to play in a Vector for example, and make a queue that will start by playing the first one and when it finishes it will start by the second.
So in ur vector you will have the test1, test2, test3, ... and you will play the test1. When this finished you will start by test2 ...

Vector v = new Vector();
v.addElement("Test(2seconds).mp3");
v.addElement("Test(2seconds)2.mp3");
v.addElement("Test(2seconds)3.mp3");
for (int i = 0 ; i < v.size() ; i ++) {
String address = (String) v.elementAt(i);
//play here the audio file
//You can use here thread.wait() and Thread.notify to handle the event of beggining of an audio file and the ending of it. Do not play them all in the same time. You have to wait for the audio file to end before playing the other one
}

Related

how to download file from server & save it to device using using blackberry api

I want to download a .txt file from http server and store it on device memory.How can i do it.I am new to it so any help would be appreciated. Thanks in advance
I am not going to code for you, But i can give you logic for it, as i have already done this kind of work.
You are going to need HttpConnection, DataInutStream,DataOutputStream and FileConnection Class for the same purpose.
Here is a link of an example, it is same as your question's requirement, you need to study it and code for your self.
Hint: Only minor changes require in that code, if you can figure it out.
Use the below code
package com.neel.java.rim.api.net;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.io.file.FileConnection;
import net.rim.device.api.ui.component.Dialog;
public class FileDownloader implements Runnable {
// Holds the URL to download the file
StringBuffer url = null;
//holds the instance of the delegate screen
protected Object delegate;
public FileDownloader(String url) {
// image URL
this.url = new StringBuffer();
this.url.append(url.toString());
}
//taking the instance of the delegate
//this is the object of the active screen from where the request is made
public Object getDelegate() {
return delegate;
}
public void setDelegate(Object delegate) {
this.delegate = delegate;
}
// Thread starts the execution
public void run() {
byte[] dataArray;
InputStream input;
//url.append(updateConnSuffix()); // ad connection suffix for the data usage
HttpConnection httpConn = null;
try {
httpConn = (HttpConnection) Connector.open(url.toString());
input = httpConn.openInputStream();
dataArray = net.rim.device.api.io.IOUtilities.streamToBytes(input);
writeFile(dataArray);
} catch (IOException e) {
e.printStackTrace();
Dialog.alert("Eoor in downloading image");
}
}
public void writeFile(byte[] data){
FileConnection fc = null;
// to save in SD Card
String pFilePath = "SDCard/BlackBerry/pictures/text.txt";
/*use below path for saving in Device Memory*/
//String pFilePath = "store/home/user/pictures/text.txt";
OutputStream lStream = null;
String time = new String();
if (pFilePath != null) {
try {
fc = (FileConnection)Connector.open("file:///" + pFilePath ,Connector.READ_WRITE);
if(null == fc || fc.exists() == false){
fc.create();
}
lStream = fc.openOutputStream(fc.fileSize());
lStream.write(data);
} catch (Exception ioex) {
ioex.printStackTrace();
} finally {
if (lStream != null) {
try {
lStream.close();
lStream = null;
} catch (Exception ioex){
}
}
if (fc != null) {
try {
fc.close();
fc = null;
} catch (Exception ioex){
}
}
}
}
}
}

BlackBerry - "Media unloaded while initializing" error

I am trying to play a video based on the videorecordingdemo sample from JDE7.0 (code below).
I am building for OS5.0 - which is why I cannot just run the whole demo app which is written for OS7.0.
I am using the emulator (9300) and have set up a folder to be used as my sd card. I have placed a .AVI video in there. I have also tried placing the .AVI into the resources, and streaming it from there.
In both cases, when I call Player.start(), the following exception is thrown:
net.rim.device.internal.media.RimMediaException: Media unloaded while initializing
I would like to know:
What does this error mean?
How can I fix it?
Alternatively are the any really special, stringent requirements for .AVI files to play?
Update: Tried the app on a real Torch device, and it gave
net.rim.device.internal.media.UnloadedMediaException
FWIW here is the sample code - as copied directly from the videorecordingdemo sample app.
package mypackage;
/*
* VideoPlaybackScreen.java
*
* Copyright © 1998-2011 Research In Motion Ltd.
*
* Note: For the sake of simplicity, this sample application may not leverage
* resource bundles and resource strings. However, it is STRONGLY recommended
* that application developers make use of the localization features available
* within the BlackBerry development platform to ensure a seamless application
* experience across a variety of languages and geographies. For more information
* on localizing your application, please refer to the BlackBerry Java Development
* Environment Development Guide associated with this release.
*/
import javax.microedition.media.Player;
import javax.microedition.media.PlayerListener;
import javax.microedition.media.control.VideoControl;
import javax.microedition.media.control.VolumeControl;
import java.io.IOException;
import java.io.InputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.file.FileConnection;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.Dialog;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.container.MainScreen;
/**
* A screen for playing a video
*/
public class VideoPlaybackScreen extends MainScreen
{
private Player _videoPlayer;
private VideoControl _videoControl;
/**
* Constructs a screen to playback the video from a specified input stream
*
* #param inputStream The InputStream of the video to display
*
* #throws NullPointerException Thrown if <code>inputStream</code> is null
*/
public VideoPlaybackScreen(InputStream inputStream)
{
if (inputStream == null)
{
throw new NullPointerException("'inputStream' cannot be null");
}
try
{
_videoPlayer = javax.microedition.media.Manager.createPlayer(inputStream, "video/sbv");
initScreen();
}
catch( Exception e )
{
Dialog.alert("Exception while initializing the playback video player\n\n" + e);
}
}
/**
* Constructs the screen to playback the video from a file
*
* #param file A locator string in URI syntax that points to the video file
*/
public VideoPlaybackScreen(String file)
{
boolean notEmpty;
try
{
FileConnection fconn = (FileConnection) Connector.open(file);
notEmpty = fconn.exists() && fconn.fileSize() > 0;
fconn.close();
}
catch( IOException e )
{
Dialog.alert("Exception while accessing the video filesize:\n\n" + e);
notEmpty = false;
}
// Initialize the player if the video is not empty
if( notEmpty )
{
try
{
_videoPlayer = javax.microedition.media.Manager.createPlayer(file);
initScreen();
}
catch( Exception e )
{
Dialog.alert("Exception while initializing the playback video player\n\n" + e);
}
}
else
{
add(new LabelField("The video file you are trying to play is empty"));
}
}
/**
* Initializes the screen after the player has been created
*
* #throws Exception Thrown if an error occurs when initializing the video player, video display or volume control
*/
private void initScreen() throws Exception
{
_videoPlayer.realize();
_videoPlayer.addPlayerListener(new PlayerListener()
{
/**
* #see javax.microedition.media.PlayerListener#playerUpdate(Player, String, Object)
*/
public void playerUpdate(Player player, String event, Object eventData)
{
// Alert the user and close the screen after the video has
// finished playing.
if( event == PlayerListener.END_OF_MEDIA )
{
UiApplication.getUiApplication().invokeLater(new Runnable()
{
public void run()
{
Dialog.alert("Finished playing");
close();
}
});
}
}
});
// Set up the playback
_videoControl = (VideoControl) _videoPlayer.getControl("VideoControl");
Field vField = (Field) _videoControl.initDisplayMode(VideoControl.USE_GUI_PRIMITIVE,
"net.rim.device.api.ui.Field");
add(vField);
VolumeControl vol = (VolumeControl) _videoPlayer.getControl("VolumeControl");
vol.setLevel(30);
}
/**
* #see net.rim.device.api.ui.Field#onVisibilityChange(boolean)
*/
protected void onVisibilityChange(boolean visible)
{
// If the screen becomes visible and the video player was created, then
// start the playback.
if( visible && _videoPlayer != null )
{
try
{
_videoPlayer.start();
}
catch( final Exception e )
{
UiApplication.getUiApplication().invokeLater(new Runnable()
{
public void run()
{
// If starting the video fails, terminate the playback
Dialog.alert("Exception while starting the video\n\n" + e);
close();
}
});
}
}
}
/**
* #see net.rim.device.api.ui.Screen#onClose()
*/
public void close()
{
// Close the video player if it was created
if( _videoPlayer != null )
{
_videoPlayer.close();
}
super.close();
}
}

How to play an audio file one after another in Blackberry?

I managed to create an application in Blackberry that plays audio file, but it will only plays one file. I try to use a for loop to play a few audio files.
I managed to play it, but it did not play the whole sound of the audio files, it just play the first audio files and second for a few seconds, and stop playing after that. The files that played also play the sound overlap each other which should not be happening.
How to play the full sound of the audio files one after another in Blackberry without stopping?
Here is my code for the application that I created with the for loop:
package mypackage;
import javax.microedition.media.Manager;
import javax.microedition.media.MediaException;
import javax.microedition.media.Player;
import java.lang.Class;
import javax.microedition.rms.RecordStore;
import java.io.InputStream;
import java.io.ByteArrayInputStream;
import net.rim.device.api.media.protocol.ByteArrayInputStreamDataSource;
import net.rim.device.api.system.*;
import net.rim.device.api.ui.*;
import net.rim.device.api.ui.component.*;
import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.ui.extension.container.*;
import net.rim.device.api.ui.UiApplication;
import java.io.IOException;
public class PlayMedia extends UiApplication{
/**
* Entry point for application
* #param args Command line arguments (not used)
*/
public static void main(String[] args){
PlayMedia theApp = new PlayMedia();
theApp.enterEventDispatcher();
}
public PlayMedia()
{
pushScreen(new PlayMediaScreen());
}
/**
* A class extending the MainScreen class, which provides default standard
* behavior for BlackBerry GUI applications.
*/
final class PlayMediaScreen extends MainScreen
{
/**
* Creates a new PlayMediaScreen object
*/
PlayMediaScreen()
{
String test1 = "Test(2seconds).mp3";
String test2 = "Test(2seconds)2.mp3";
String test3 = "Test(2seconds)3.mp3";
String test4 = "Test(2seconds)4.mp3";
String test5 = "blind_willie.mp3";
String mp3 = null;
for(int i=0;i<5;i++){
if(i == 0){
mp3 = test1;
}
else if(i == 1){
mp3 = test2;
}
else if(i == 2){
mp3 = test3;
}
else if(i == 3){
mp3 = test4;
}
else if(i == 4){
mp3 = test5;
}
play(mp3);
}
}
private void play(String mp3){
Player p = null;
InputStream stream = (InputStream)this.getClass().getResourceAsStream("/" + mp3);
try {
//p = Manager.createPlayer(source);
p = Manager.createPlayer(stream, "audio/mpeg");
p.realize();
p.prefetch();
//testing
System.out.println("Creating Players!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
System.out.println("The mp3 is " + mp3 + "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
//testing
System.out.println("IO Exeception!!!!!!!!!!!!!!!!1 " + e);
//testing
System.out.println(p);
} catch (MediaException e) {
// TODO Auto-generated catch block
e.printStackTrace();
//testing
System.out.println("Media Exeception!!!!!!!!!!!!!!!!1" + e);
//testing
System.out.println(p);
}
/*
* Best practice is to invoke realize(), then prefetch(), then start().
* Following this sequence reduces delays in starting media playback.
*
* Invoking start() as shown below will cause start() to invoke prefetch(0),
* which invokes realize() before media playback is started.
*/
try {
p.start();
} catch (MediaException e) {
// TODO Auto-generated catch block
e.printStackTrace();
//testing
System.out.println("Media Exeception for starting!!!!!!!!!!!!!!!!1" + e);
//testing
System.out.println(p);
}
/*try {
p.stop();
} catch (MediaException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
//p.deallocate();
//p.close();
}
}
}
I managed to play it, but it did not play the whole sound of the audio files, it just play the first audio files and second for a few seconds, and stop playing after that. The files that played also play the sound overlap each other which should not be happening.
Please reread the BB API docs for Player carefully:
Simple Playback
A Player can be created from one of the Manager's createPlayer methods. After the Player is created, calling start will start the playback as soon as possible. The method will return when the playback is started. The playback will continue in the background and will stop automatically when the end of media is reached.
Simple playback example illustrates this:
try {
Player p = Manager.createPlayer("http://abc.wav");
p.start();
} catch (MediaException pe) {
} catch (IOException ioe) {
}
Note the docs say The method will return when the playback is started. The playback will continue in the background ... This is the reason of you get "sound overlap".
To overcome this you need to attach a listener to the player Player.addPlayerListener(PlayerListener playerListener). The listener will be notified from the background "playback" thread when the media file has been played to the end. And this will be the right moment to start a new playback for the next media file. Please don't expect the code from me, I'm just giving you an idea.
Finally I get it, this is my code. :D
package mypackage;
import javax.microedition.media.Manager;
import javax.microedition.media.MediaException;
import javax.microedition.media.Player;
import javax.microedition.media.PlayerListener;
import java.lang.Class;
import javax.microedition.rms.RecordStore;
import java.io.InputStream;
import java.io.ByteArrayInputStream;
import net.rim.device.api.media.protocol.ByteArrayInputStreamDataSource;
import net.rim.device.api.system.*;
import net.rim.device.api.ui.*;
import net.rim.device.api.ui.component.*;
import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.ui.extension.container.*;
import net.rim.device.api.ui.UiApplication;
import java.io.IOException;
public class PlayMedia extends UiApplication{
/**
* Entry point for application
* #param args Command line arguments (not used)
*/
public static void main(String[] args){
PlayMedia theApp = new PlayMedia();
theApp.enterEventDispatcher();
}
public PlayMedia()
{
pushScreen(new PlayMediaScreen());
}
/**
* A class extending the MainScreen class, which provides default standard
* behavior for BlackBerry GUI applications.
*/
final class PlayMediaScreen extends MainScreen implements PlayerListener
{
/**
* Creates a new PlayMediaScreen object
*/
Player p = null;
String mp3 = "";
String test1 = "Test2seconds.mp3";
String test5 = "Test2seconds2.mp3";
//String test6 = "Test2seconds3.mp3";
String test4 = "Test2seconds4.mp3";
String test2 = "blind_willie.mp3";
String test3 = "blind_willie2.mp3";
PlayMediaScreen()
{
mp3 = test1;
play(mp3);
}
private void play(String mp3){
InputStream stream = (InputStream)this.getClass().getResourceAsStream("/" + mp3);
try {
//p = Manager.createPlayer(source);
p = Manager.createPlayer(stream,"audio/mpeg");
p.addPlayerListener(this);
p.realize();
p.prefetch();
//testing
System.out.println("Creating Players!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
System.out.println("The mp3 is " + mp3 + "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
//testing
System.out.println("IO Exeception!!!!!!!!!!!!!!!!1 " + e);
//testing
System.out.println(p);
} catch (MediaException e) {
// TODO Auto-generated catch block
e.printStackTrace();
//testing
System.out.println("Media Exeception!!!!!!!!!!!!!!!!1" + e);
//testing
System.out.println(p);
}
/*
* Best practice is to invoke realize(), then prefetch(), then start().
* Following this sequence reduces delays in starting media playback.
*
* Invoking start() as shown below will cause start() to invoke prefetch(0),
* which invokes realize() before media playback is started.
*/
try {
p.start();
} catch (MediaException e) {
// TODO Auto-generated catch block
e.printStackTrace();
//testing
System.out.println("Media Exeception for starting!!!!!!!!!!!!!!!!1" + e);
//testing
System.out.println(p);
}
/*
try {
p.stop();
} catch (MediaException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
p.deallocate();
p.close();
*/
}
public void playerUpdate(Player player, String event, Object eventData) {
// TODO Auto-generated method stub
if (event.equals(PlayerListener.END_OF_MEDIA)) {
//String mp3 = "";
if( mp3.equals(test1) ) {
mp3 = test2;
//testing
System.out.println("The MP3 is " + mp3 + "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
play(mp3);
//testing
System.out.println("The MP3 FINISH PLAYING is " + mp3 + "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
}
else if( mp3.equals(test2) ){
mp3 = test3;
//testing
System.out.println("The MP3 is " + mp3 + "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
play(mp3);
//testing
System.out.println("The MP3 FINISH PLAYING is " + mp3 + "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
}
else if( mp3.equals(test3) ) {
mp3 = test4;
//testing
System.out.println("The MP3 is " + mp3 + "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
play(mp3);
//testing
System.out.println("The MP3 FINISH PLAYING is " + mp3 + "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
}
else if( mp3.equals(test4) ) {
mp3 = test5;
//testing
System.out.println("The MP3 is " + mp3 + "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
play(mp3);
//testing
System.out.println("The MP3 FINISH PLAYING is " + mp3 + "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
}
else if( mp3.equals(test5) ){
mp3 = null;
try {
player.stop();
} catch (MediaException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
player.deallocate();
player.close();
}
}
}
}
}

send sms from background thread in blackberry using j2me

hey i made a lot of search and found some similar types of code.
I tried for gsm
method 1 gives IllegalArgumentException
try
{
MessageConnection _mc = (MessageConnection)Connector.open("sms://");
TextMessage tm = (TextMessage) _mc.newMessage(MessageConnection.TEXT_MESSAGE);
tm.setPayloadText(smsText);
tm.setAddress("965xxxxxxx");
_mc.send(tm);
_mc.close();
}catch(exception e){}
method 2: gives java.lang.error exception
try
{
MessageConnection _mc = (MessageConnection)Connector.open("sms://");
TextMessage tm = (TextMessage) _mc.newMessage(MessageConnection.TEXT_MESSAGE,
"//9790XXXXXX");
tm.setPayloadText(text);
_mc.send(tm);
_mc.close();
}catch(Exception e){}
I think the problem is with address
i also tried : but no success
+91965xxxxxxx ,
0091965xxxxxxx ,
0965xxxxxxx
How my application works----
i have created 2 applications--
1) Application 1 is a background app that is a System module as well as
startup application.
2) Another is a uiapplication
the background app runs in background.If there comes an incoming call then a flag value is set in persistent object and after checking that value as true the sms is send to that no from whom call is made.
ok try this
import java.io.IOException;
import javax.microedition.io.Connector;
import javax.microedition.io.Datagram;
import javax.microedition.io.DatagramConnection;
import javax.wireless.messaging.MessageConnection;
import javax.wireless.messaging.TextMessage;
import net.rim.device.api.system.RadioInfo;
public class SendSMS extends Thread {
private String to;
private String msg;
public SendSMS(String to, String msg) {
this.to = to;
this.msg = msg;
}
public void run() {
if (RadioInfo.getNetworkType() == RadioInfo.NETWORK_CDMA) {
DatagramConnection dc = null;
try {
dc = (DatagramConnection) Connector.open("sms://" + to);
byte[] data = msg.getBytes();
Datagram dg = dc.newDatagram(dc.getMaximumLength());
dg.setData(data, 0, data.length);
dc.send(dg);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
dc.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
} else {
MessageConnection mc = null;
try {
mc = (MessageConnection) Connector
.open("sms://" + to);
TextMessage m = (TextMessage) mc
.newMessage(MessageConnection.TEXT_MESSAGE);
m.setPayloadText(msg);
mc.send(m);
} catch (IOException e1) {
e1.printStackTrace();
} finally {
try {
mc.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
}
}
and call like this
public void callDisconnected(int callId) {
final PhoneCall call = Phone.getCall(callId);
final String number = call.getDisplayPhoneNumber();
SendSMS sendSMS = new SendSMS(number, "message");
sendSMS.start();
super.callDisconnected(callId);
}

How to send audio data from Java Applet to Rails controller

I have to send the audio data in byte array obtain by recording from java applet at the client side to rails server at the controller in order to save.
So, what encoding parameters at the applet side be used and in what form the audio data be converted like String or byte array so that rails correctly recieve data and then I can save that data at the rails in the file. As currently the audio file made by rails controller is not playing. It is the following ERROR :
LAVF_header: av_open_input_stream() failed
while playing with the mplayer.
Here is the sample Java Code i m using in which i m reading audio data from the audio file:
package networksocket;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JApplet;
import java.net.*;
import java.io.*;
import java.awt.event.*;
import java.awt.*;
import java.sql.*;
import javax.swing.*;
import javax.swing.border.*;
import java.awt.*;
import java.util.Properties;
import javax.swing.plaf.basic.BasicSplitPaneUI.BasicHorizontalLayoutManager;
import sun.awt.HorizBagLayout;
import sun.awt.VerticalBagLayout;
import sun.misc.BASE64Encoder;
/**
*
* #author mukand
*/
public class Urlconnection extends JApplet implements ActionListener
{
/**
* Initialization method that will be called after the applet is loaded
* into the browser.
*/
public BufferedInputStream in;
public BufferedOutputStream out;
public String line;
public FileOutputStream file;
public int bytesread;
public int toread=1024;
byte b[]= new byte[toread];
public String f="FINISH";
public String match;
public File fileopen;
public JTextArea jTextArea;
public Button refreshButton;
public HttpURLConnection urlConn;
public URL url;
OutputStreamWriter wr;
BufferedReader rd;
#Override
public void init() {
// TODO start asynchronous download of heavy resources
//textField= new TextField("START");
//getContentPane().add(textField);
JPanel p = new JPanel();
jTextArea= new JTextArea(1500,1500);
p.setLayout(new GridLayout(1,1, 1,1));
p.add(new JLabel("Server Details"));
p.add(jTextArea);
Container content = getContentPane();
content.setLayout(new GridBagLayout()); // Used to center the panel
content.add(p);
jTextArea.setLineWrap(true);
refreshButton = new java.awt.Button("Refresh");
refreshButton.reshape(287,49,71,23);
refreshButton.setFont(new Font("Dialog", Font.PLAIN, 12));
refreshButton.addActionListener(this);
add(refreshButton);
Properties properties = System.getProperties();
properties.put("http.proxyHost", "netmon.iitb.ac.in");
properties.put("http.proxyPort", "80");
}
#Override
public void actionPerformed(ActionEvent e)
{
try
{
url = new URL("http://localhost:3000/audio/audiorecieve");
urlConn = (HttpURLConnection)url.openConnection();
//String login = "mukandagarwal:rammstein$";
//String encodedLogin = new BASE64Encoder().encodeBuffer(login.getBytes());
//urlConn.setRequestProperty("Proxy-Authorization",login);
urlConn.setRequestMethod("POST");
// urlConn.setRequestProperty("Content-Type",
//"application/octet-stream");
//urlConn.setRequestProperty("Content-Type","audio/mpeg");//"application/x-www- form-urlencoded");
//urlConn.setRequestProperty("Content-Type","application/x-www- form-urlencoded");
//urlConn.setRequestProperty("Content-Length", "" +
// Integer.toString(urlParameters.getBytes().length));
urlConn.setRequestProperty("Content-Language", "UTF-8");
urlConn.setDoOutput(true);
urlConn.setDoInput(true);
byte bread[]=new byte[2048];
int iread;
char c;
String data=URLEncoder.encode("key1", "UTF-8")+ "=";
//String data="key1=";
FileInputStream fileread= new FileInputStream("//home//mukand//Hellion.ogg");//Dogs.mp3");//Desktop//mausam1.mp3");
while((iread=fileread.read(bread))!=-1)
{
//data+=(new String());
/*for(int i=0;i<iread;i++)
{
//c=(char)bread[i];
System.out.println(bread[i]);
}*/
data+= URLEncoder.encode(new String(bread,iread), "UTF-8");//new String(new String(bread));//
// data+=new String(bread,iread);
}
//urlConn.setRequestProperty("Content-Length",Integer.toString(data.getBytes().length));
System.out.println(data);
//data+=URLEncoder.encode("mukand", "UTF-8");
//data += "&" + URLEncoder.encode("key2", "UTF-8") + "=" + URLEncoder.encode("value2", "UTF-8");
//data="key1=";
wr = new OutputStreamWriter(urlConn.getOutputStream());//urlConn.getOutputStream();
//if((iread=fileread.read(bread))!=-1)
// wr.write(bread,0,iread);
wr.write(data);
wr.flush();
fileread.close();
jTextArea.append("Send");
// Get the response
rd = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
while ((line = rd.readLine()) != null) {
jTextArea.append(line);
}
wr.close();
rd.close();
//jTextArea.append("click");
}
catch (MalformedURLException ex) {
Logger.getLogger(Urlconnection.class.getName()).log(Level.SEVERE, null, ex);
}
catch (IOException ex) {
Logger.getLogger(Urlconnection.class.getName()).log(Level.SEVERE, null, ex);
}
}
#Override
public void start()
{
}
#Override
public void stop()
{
}
#Override
public void destroy()
{
}
// TODO overwrite start(), stop() and destroy() methods
}
Here is the Rails controller function for recieving:
def audiorecieve
puts "///////////////////////////////////////******RECIEVED*******////"
puts params[:key1]#+" "+params[:key2]
data=params[:key1]
#request.env('RAW_POST_DATA')
file=File.new("audiodata.ogg", 'w')
file.write(data)
file.flush
file.close
puts "////**************DONE***********//////////////////////"
end
Please reply quickly
Base64 encode the data. Send it as a string, receive it on the Rails side and decode it back to the original format.

Resources