views:

37

answers:

1

Hi, 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 code i m using in which i m reading audio data from the audio file. Here is the Java Code: 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

A: 

Base64 encode the data. Send it as a string, receive it on the Rails side and decode it back to the original format.

x1a4
@x1a4: What should be set for Content-Type ,Content-Language parameters of the httpurlconnection object.
cooldude
Use text/plain for content type. That's why I gave the Base64 suggestion. Then you're just dealing with string data. Pass it as a normal post parameter. Use ascii for the encoding.
x1a4
@x1a4: Thanks for your help. The thing worked.
cooldude
@x1a4: Now i m having one more problem. My audio can be of any size. It can exceed the limit. I want to fragment my audio data in chunks and then send it while the connection is still on. But rails is taking it only for the first data send.
cooldude
Exceed what limit? If you use http POST, there is no limit to the size of a post param.If for some reason you really do need to split it, just break it up into chunks of n characters, send the chunks (you'll need to keep track of their ordering as well if you do this), then reassemble them on the server side in the correct order.
x1a4
@x1a4: Using Httpurlconnecttion , the rails server is accepting only the first data chunk send. If the file is send at one time by declaring the size of byte array, then the memory of client can be give up.
cooldude
@x1a4: I m using the while loop to continously read the data and the send it and then again read. But rails server is accepting only the first send.
cooldude
Maybe make sure the request isn't closing after each loop? I don't do java, sorry. The original question was about serialization and deserialization of binary data over the wire between your applet and Rails, and has changed a bit since then.
x1a4
@x1a4: Thanks for your great help. I have sorted out and finally it is working now. No need to be sorry.
cooldude
nice! glad it's working for you now.
x1a4