简体   繁体   English

Java类作为应用程序工作,但不作为applet工作

[英]Java class working as an application but not as an applet

I am an android developer and do not have extensive knowledge about java web development, so please bear with me if the question is a little weird. 我是一个Android开发人员,并且没有关于java web开发的广泛知识,所以如果问题有点奇怪,请耐心等待。 I have created a java class which is supposed to receive data packets in form of audio from an android app and plays it on PC speakers. 我创建了一个java类,它应该从Android应用程序接收音频形式的数据包并在PC扬声器上播放。 The application is basically a streaming app from phone to server. 该应用程序基本上是从手机到服务器的流媒体应用程序 The class is running fine as an application. 该类作为应用程序正常运行。

Here is the code for the class : 这是该类代码

class Server {

AudioInputStream audioInputStream;
static AudioInputStream ais;
static AudioFormat format;
static boolean status = true;
static int port = 50005;
static int sampleRate = 8000;



public static void main(String args[]) throws Exception {


    DatagramSocket serverSocket = new DatagramSocket(50005);

    /**
     * Formula for lag = (byte_size/sample_rate)*2
     * Byte size 9728 will produce ~ 0.45 seconds of lag. Voice slightly broken.
     * Byte size 1400 will produce ~ 0.06 seconds of lag. Voice extremely broken.
     * Byte size 4000 will produce ~ 0.18 seconds of lag. Voice slightly more broken then 9728.
     */

    byte[] receiveData = new byte[5000];

    format = new AudioFormat(sampleRate, 16, 1, true, false);

    while (status == true) {
        DatagramPacket receivePacket = new DatagramPacket(receiveData,
                receiveData.length);

        serverSocket.receive(receivePacket);

        ByteArrayInputStream baiss = new ByteArrayInputStream(
                receivePacket.getData());

        ais = new AudioInputStream(baiss, format, receivePacket.getLength());
        toSpeaker(receivePacket.getData());

    }



}

public static void toSpeaker(byte soundbytes[]) {
    try {

        DataLine.Info dataLineInfo = new DataLine.Info(SourceDataLine.class, format);
        SourceDataLine sourceDataLine = (SourceDataLine) AudioSystem.getLine(dataLineInfo);

        sourceDataLine.open(format);

        FloatControl volumeControl = (FloatControl) sourceDataLine.getControl(FloatControl.Type.MASTER_GAIN);
        volumeControl.setValue(6.0206f);

        sourceDataLine.start();
        sourceDataLine.open(format);

        sourceDataLine.start();

        System.out.println("format? :" + sourceDataLine.getFormat());

        sourceDataLine.write(soundbytes, 0, soundbytes.length);
        System.out.println(soundbytes.toString());
        sourceDataLine.drain();
        sourceDataLine.close();
    } catch (Exception e) {
        System.out.println("Not working in speakers...");
        e.printStackTrace();
    }
}
}

Now I wanted to convert the class into an applet such that I can deploy the same as a web application. 现在我想将类转换为applet,以便我可以将其部署为Web应用程序。 Here is the code for the applet : 这是applet代码

public class AppletTest extends Applet {


    AudioInputStream audioInputStream;
    static AudioInputStream ais;
    static AudioFormat format;
    static boolean status = true;
    static int port = 50005;
    static int sampleRate = 8000;



    public void init()
    {

    }

    public void stop()
    {

    }



    public void listening()
    {
         DatagramSocket serverSocket = null;
        try {
            serverSocket = new DatagramSocket(50005);
        } catch (SocketException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

            /**
             * Formula for lag = (byte_size/sample_rate)*2
             * Byte size 9728 will produce ~ 0.45 seconds of lag. Voice slightly broken.
             * Byte size 1400 will produce ~ 0.06 seconds of lag. Voice extremely broken.
             * Byte size 4000 will produce ~ 0.18 seconds of lag. Voice slightly more broken then 9728.
             */

            byte[] receiveData = new byte[5000];

            format = new AudioFormat(sampleRate, 16, 1, true, false);

            while (status == true) {
                DatagramPacket receivePacket = new DatagramPacket(receiveData,
                        receiveData.length);

                try {
                    serverSocket.receive(receivePacket);
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                ByteArrayInputStream baiss = new ByteArrayInputStream(
                        receivePacket.getData());

                ais = new AudioInputStream(baiss, format, receivePacket.getLength());
                toSpeaker(receivePacket.getData());

            }
    }



    public static void toSpeaker(byte soundbytes[]) {
        try {

            DataLine.Info dataLineInfo = new DataLine.Info(SourceDataLine.class, format);
            SourceDataLine sourceDataLine = (SourceDataLine) AudioSystem.getLine(dataLineInfo);

            sourceDataLine.open(format);

            FloatControl volumeControl = (FloatControl) sourceDataLine.getControl(FloatControl.Type.MASTER_GAIN);
            volumeControl.setValue(6.0206f);

            sourceDataLine.start();
            sourceDataLine.open(format);

            sourceDataLine.start();

            System.out.println("format? :" + sourceDataLine.getFormat());

            sourceDataLine.write(soundbytes, 0, soundbytes.length);
            System.out.println(soundbytes.toString());
            sourceDataLine.drain();
            sourceDataLine.close();
        } catch (Exception e) {
            System.out.println("Not working in speakers...");
            e.printStackTrace();
        }
    }


}

The html code to call the applet : 用于调用applethtml代码

<HTML>
<TITLE>Applet Test</TITLE>
<HEAD></HEAD>
<BODY>
<applet code="AppletTest.class" height="200" width="500">Applet</applet>
</BODY>
</HTML>

I have hosted the applet here 我在这里托管了applet

This is the android activity to send sound in form of datapackets : 这是以数据包形式发送声音android活动

public class SendActivity extends Activity {
    private Button startButton, stopButton;

    public byte[] buffer;
    public static DatagramSocket socket;
    private int port = 50005;
    AudioRecord recorder;

    private int sampleRate = 8000;
    @SuppressWarnings("deprecation")
    private int channelConfig = AudioFormat.CHANNEL_IN_MONO;
    private int audioFormat = AudioFormat.ENCODING_PCM_16BIT;
    int minBufSize = AudioRecord.getMinBufferSize(sampleRate, channelConfig,
            audioFormat);
    private boolean status = true;


    int bufferSizeInBytes;
    int bufferSizeInShorts;
      int shortsRead;
      short audioBuffer[];

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_send);

        startButton = (Button) findViewById(R.id.start_button);
        stopButton = (Button) findViewById(R.id.stop_button);

        startButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                status = true;
                startStreaming();


            }

        });

        stopButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                status = false;
                recorder.release();
                Log.d("VS", "Recorder released");

            }

        });

        minBufSize += 5120;
        System.out.println("minBufSize: " + minBufSize);
    }


    public void startStreaming() {

        Thread streamThread = new Thread(new Runnable() {

            @Override
            public void run() {
                try {

                    DatagramSocket socket = new DatagramSocket();
                    Log.d("VS", "Socket Created");

                    byte[] buffer = new byte[minBufSize];

                    Log.d("VS", "Buffer created of size " + minBufSize);
                    DatagramPacket packet;

                    final InetAddress destination = InetAddress
                            .getByName("http://abhideepmallick.byethost16.com/");

//final InetAddress destination = InetAddress.getByName("192.168.1.20");//machine IP

Log.d("VS", "Address retrieved");

                    recorder = new AudioRecord(MediaRecorder.AudioSource.VOICE_RECOGNITION,
                            sampleRate, channelConfig, audioFormat,
                            minBufSize * 10);
                    Log.d("VS", "Recorder initialized");

                    recorder.startRecording();

                    while (status == true) {

                        // reading data from MIC into buffer
                        minBufSize = recorder.read(buffer, 0, buffer.length);

                        // putting buffer in the packet
                        packet = new DatagramPacket(buffer, buffer.length,
                                destination, port);

                        socket.send(packet);
                        System.out.println("MinBufferSize: " + minBufSize);

                    }

                } catch (UnknownHostException e) {
                    Log.e("VS", "UnknownHostException");
                } catch (IOException e) {
                    e.printStackTrace();
                    Log.e("VS", "IOException");
                }
            }

        });
        streamThread.start();
    }


}

Android layout file : Android 布局文件

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".SendActivity" >



    <Button
        android:id="@+id/stop_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/start_button"
        android:layout_alignBottom="@+id/start_button"
        android:layout_toRightOf="@+id/start_button"
        android:text="Stop" />

    <Button
        android:id="@+id/start_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="79dp"
        android:layout_marginTop="163dp"
        android:text="Start" />

</RelativeLayout>

What should I do to make the java class work as an applet? 我该怎么做才能使java类作为applet工作?

I suppose you managed that the java plugin for the browser is up to date, in order to start the applet. 我想你管理浏览器的java插件是最新的,以便启动applet。

An applet has also a lifecylce like a activity. applet也像活动一样具有生命力。

The init() method is like a constructor, and the purpose of the start() method is to inform the applet should start executing. init()方法就像一个构造函数,start()方法的目的是通知applet应该开始执行。

So override the start method and call your listening method from there. 因此,重写start方法并从那里调用您的监听方法。 For more information you could browse through this slide: http://de.slideshare.net/myrajendra/applet-life-cycle 有关更多信息,您可以浏览此幻灯片: http//de.slideshare.net/myrajendra/applet-life-cycle

An example can be found here: http://www.ugrad.cs.ubc.ca/~cs219/CourseNotes/Java/applets/lifecycle.html 可以在这里找到一个例子: http//www.ugrad.cs.ubc.ca/~cs219/CourseNotes/Java/applets/lifecycle.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM