DatagramSocket将audiocall发送到其他Android设备

时间:2013-10-30 12:39:16

标签: java android eclipse

我正在制作一个Android应用程序来使用IP地址调用其他Android设备。我这里有代码用于发送音频呼叫,但它在java中。我想在Android中尝试这个。此代码来自Java代码。

以下是代码:

MainActivity.java

import java.net.DatagramSocket;

import javax.swing.DefaultListModel;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

import com.example.voip.Microphone;
import com.example.voip.Speaker;
public class MainActivity extends Activity {
     DatagramSocket sock = null;
     DefaultListModel<String> on = null;
     Button btnStart;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnStart = (Button) findViewById(R.id.btnStart);
        btnStart.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                disp();
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

    public void disp(){
        on = new DefaultListModel<String>();
           on.addElement("192.168.1.100");
            try{
                sock = new DatagramSocket(4003);
            }catch(Exception e){

            }
            Thread speaker = new Thread(new Speaker(sock));
            Thread mic = new Thread(new Microphone(sock, 4003, on));
            speaker.start();
            mic.start();
    }
}

Microphone.java

package com.example.voip;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.ArrayList;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.TargetDataLine;
import javax.swing.DefaultListModel;

import android.content.pm.PackageManager;




public class Microphone implements Runnable{

    private DatagramSocket sock = null;
    private int port = 0;
    private DefaultListModel<String> on = null;

    public Microphone(DatagramSocket d,int recPort,DefaultListModel<String> joi) {
        this.sock = d;
        this.on = joi;
        this.port =recPort;
    }

    @Override
    public void run(){
        try {
            AudioFormat af = new AudioFormat(8000.0f, 8, 1, true, false);
            DataLine.Info info = new DataLine.Info(TargetDataLine.class, af);
            TargetDataLine microphone = (TargetDataLine) AudioSystem.getLine(info);

            microphone.open(af);
            microphone.start();

            byte[] soundData = new byte[1];
            int bytesRead = 0;
            while (bytesRead != -1) {
                bytesRead = microphone.read(soundData, 0, soundData.length);

                if (bytesRead >= 0) {
                    for (int y = 0; y < on.size(); y++) {
                        DatagramPacket pac = new DatagramPacket(soundData,
                                soundData.length,
                                InetAddress.getByName(on.getElementAt(y).toString()),
                                port);
                        sock.send(pac);
                    }
                }
                Thread.sleep(0);
            }

        } catch (Exception e) {
        }
    }

    /**
     * @param sock the sock to set
     */
    public void setSock(DatagramSocket sock) {
        this.sock = sock;
    }

    /**
     * @param port the port to set
     */
    public void setPort(int port) {
        this.port = port;
    }

    /**
     * @param on the on to set
     */
    public void setOn(DefaultListModel<String> on) {
        this.on = on;
    }
}

Speaker.java

package com.example.voip;


import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.SourceDataLine;

public class Speaker implements Runnable {

    private DatagramSocket soc = null;
    DatagramPacket pack = null;
    SourceDataLine inSpeaker = null;




    public Speaker(DatagramSocket s) {

        try {
            this.soc = s;
            AudioFormat af = new AudioFormat(8000.0f, 8, 1, true, false);
            DataLine.Info info = new DataLine.Info(SourceDataLine.class, af);
            inSpeaker = (SourceDataLine) AudioSystem.getLine(info);
            inSpeaker.open(af);
            System.out.println("Speak");
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }




    public void run() {
        int bytesRead = 1;
        byte[] inSound = new byte[1];
        inSpeaker.start();
        while (bytesRead != -1) {
            pack = new DatagramPacket(inSound, inSound.length);

            try {
                soc.receive(pack);
                if (bytesRead >= 0) {
                inSpeaker.write(inSound, 0, bytesRead);
                }

            } catch (IOException ex) {
                System.out.println(ex.getMessage());
            }
        }
    }

    /**
     * @param soc the soc to set
     */
    public void setSoc(DatagramSocket soc) {
        this.soc = soc;
    }



}

activity_main.xml中

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="20dip">

    <ImageView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_launcher"
        android:scaleType="fitCenter"/>

        <TextView  
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Info"
        android:layout_weight="1.0"
        android:textSize="20dip"/>

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">

        <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/btnStart"
                android:text="Start Recording"
                android:layout_weight="1.0"/>

                <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/btnStop"
                android:text="Stop Recording"
                android:layout_weight="1.0"/>
    </LinearLayout>
</LinearLayout>

的AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.call"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="16"
        android:targetSdkVersion="16" />
    <uses-permission android:name="android.permission.USE_SIP" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.VIBRATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.RECORD_AUDIO" />

    <uses-feature android:name="android.hardware.microphone" android:required="true"/>
    <uses-feature android:name="android.hardware.wifi" android:required="true" />


    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.call.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

ERROR:

10-30 21:07:11.939: W/dalvikvm(16081): threadid=1: thread exiting with uncaught exception (group=0x40dbd908)
10-30 21:07:11.943: E/AndroidRuntime(16081): FATAL EXCEPTION: main
10-30 21:07:11.943: E/AndroidRuntime(16081): java.lang.NoClassDefFoundError: javax.swing.DefaultListModel
10-30 21:07:11.943: E/AndroidRuntime(16081):    at com.example.call.MainActivity.disp(MainActivity.java:43)
10-30 21:07:11.943: E/AndroidRuntime(16081):    at com.example.call.MainActivity$1.onClick(MainActivity.java:30)
10-30 21:07:11.943: E/AndroidRuntime(16081):    at android.view.View.performClick(View.java:4091)
10-30 21:07:11.943: E/AndroidRuntime(16081):    at android.view.View$PerformClick.run(View.java:17072)
10-30 21:07:11.943: E/AndroidRuntime(16081):    at android.os.Handler.handleCallback(Handler.java:615)
10-30 21:07:11.943: E/AndroidRuntime(16081):    at android.os.Handler.dispatchMessage(Handler.java:92)
10-30 21:07:11.943: E/AndroidRuntime(16081):    at android.os.Looper.loop(Looper.java:153)
10-30 21:07:11.943: E/AndroidRuntime(16081):    at android.app.ActivityThread.main(ActivityThread.java:5086)
10-30 21:07:11.943: E/AndroidRuntime(16081):    at java.lang.reflect.Method.invokeNative(Native Method)
10-30 21:07:11.943: E/AndroidRuntime(16081):    at java.lang.reflect.Method.invoke(Method.java:511)
10-30 21:07:11.943: E/AndroidRuntime(16081):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:821)
10-30 21:07:11.943: E/AndroidRuntime(16081):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:584)
10-30 21:07:11.943: E/AndroidRuntime(16081):    at dalvik.system.NativeStart.main(Native Method)

我的问题是当我运行应用程序然后单击开始按钮时,它总是崩溃并说“不幸的是,等等等等已经停止”。有没有办法使用这个代码?请帮忙。 =(

提前致谢。

1 个答案:

答案 0 :(得分:0)

导入

 javax.sound.sampled.AudioFormat;
 javax.sound.sampled.AudioSystem;
 javax.sound.sampled.DataLine;
 javax.sound.sampled.SourceDataLine;

打包到您的项目(如果可能),否则使用Android Audio API