TCP/UDP语音传输功能实现

UDP

发送端代码:

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.SourceDataLine;
public class AudioSender {
    private DatagramSocket socket;
    private InetAddress address;
    private int port;
    private boolean running;
    private SourceDataLine line;
    public AudioSender(String ipAddress, int port) {
        try {
            this.socket = new DatagramSocket();
            this.address = InetAddress.getByName(ipAddress);
            this.port = port;
            this.running = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public void start() {
        try {
            AudioFormat format = new AudioFormat(8000.0f, 16, 1, true, true);
            DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);
            this.line = (SourceDataLine) AudioSystem.getLine(info);
            this.line.open(format);
            this.line.start();
            byte[] buffer = new byte[1024];
            DatagramPacket packet = new DatagramPacket(buffer, buffer.length, this.address, this.port);
            while (this.running) {
                int count = this.line.read(buffer, 0, buffer.length);
                if (count > 0) {
                    packet.setData(buffer);
                    packet.setLength(count);
                    this.socket.send(packet);
                }
            }
            this.line.drain();
            this.line.stop();
            this.socket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public void stop() {
        this.running = false;
    }
    public static void main(String[] args) {
        AudioSender sender = new AudioSender("127.0.0.1", 8000);
        sender.start();
    }
}

接收端代码:

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.TargetDataLine;
public class AudioReceiver {
    private DatagramSocket socket;
    private int port;
    private boolean running;
    private TargetDataLine line;
    public AudioReceiver(int port) {
        try {
            this.socket = new DatagramSocket(port);
            this.port = port;
            this.running = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public void start() {
        try {
            AudioFormat format = new AudioFormat(8000.0f, 16, 1, true, true);
            DataLine.Info info = new DataLine.Info(TargetDataLine.class, format);
            this.line = (TargetDataLine) AudioSystem.getLine(info);
            this.line.open(format);
            this.line.start();
            byte[] buffer = new byte[1024];
            DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
            while (this.running) {
                this.socket.receive(packet);
                byte[] data = packet.getData();
                int length = packet.getLength();
                if (length > 0) {
                    this.line.write(data, 0, length);
                }
            }
            this.line.drain();
            this.line.stop();
            this.socket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public void stop() {
        this.running = false;
    }
    public static void main(String[] args) {
        AudioReceiver receiver = new AudioReceiver(8000);
        receiver.start();
    }
}

这段代码实现了一个简单的音频发送器和接收器,可以把麦克风输入的音频数据通过UDP协议发送出去,并在接收端播放出来。其中,AudioFormat 和 DataLine.Info 是用于配置音频输入输出的参数,具体可以根据实际需求进行调整。start() 方法中,发送端通过读取麦克风输入的音频数据,将其存储到 DatagramPacket 对象中,并通过 DatagramSocket 发送出去;接收端通过 DatagramSocket 接收数据,并将数据写入到音频输出设备中播放。stop() 方法用于停止发送和接收数据。注意,这段代码中没有对数据进行加密和解密,实际应用中需要考虑安全性问题。

TCP

发送端代码:

import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.SourceDataLine;
public class AudioSender {
    private Socket socket;
    private OutputStream outputStream;
    private boolean running;
    private SourceDataLine line;
    public AudioSender(String ipAddress, int port) {
        try {
            this.socket = new Socket(ipAddress, port);
            this.outputStream = this.socket.getOutputStream();
            this.running = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public void start() {
        try {
            AudioFormat format = new AudioFormat(8000.0f, 16, 1, true, true);
            DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);
            this.line = (SourceDataLine) AudioSystem.getLine(info);
            this.line.open(format);
            this.line.start();
            byte[] buffer = new byte[1024];
            while (this.running) {
                int count = this.line.read(buffer, 0, buffer.length);
                if (count > 0) {
                    this.outputStream.write(buffer, 0, count);
                }
            }
            this.line.drain();
            this.line.stop();
            this.outputStream.close();
            this.socket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public void stop() {
        this.running = false;
    }
    public static void main(String[] args) {
        AudioSender sender = new AudioSender("127.0.0.1", 8000);
        sender.start();
    }
}

接收端代码:

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.TargetDataLine;
public class AudioReceiver {
    private ServerSocket serverSocket;
    private Socket socket;
    private InputStream inputStream;
    private boolean running;
    private TargetDataLine line;
    public AudioReceiver(int port) {
        try {
            this.serverSocket = new ServerSocket(port);
            this.socket = this.serverSocket.accept();
            this.inputStream = this.socket.getInputStream();
            this.running = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public void start() {
        try {
            AudioFormat format = new AudioFormat(8000.0f, 16, 1, true, true);
            DataLine.Info info = new DataLine.Info(TargetDataLine.class, format);
            this.line = (TargetDataLine) AudioSystem.getLine(info);
            this.line.open(format);
            this.line.start();
            byte[] buffer = new byte[1024];
            while (this.running) {
                int count = this.inputStream.read(buffer, 0, buffer.length);
                if (count > 0) {
                    this.line.write(buffer, 0, count);
                }
            }
            this.line.drain();
            this.line.stop();
            this.inputStream.close();
            this.socket.close();
            this.serverSocket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public void stop() {
        this.running = false;
    }
    public static void main(String[] args) {
        AudioReceiver receiver = new AudioReceiver(8000);
        receiver.start();
    }
}

这段代码实现了一个简单的音频发送器和接收器,可以把麦克风输入的音频数据通过TCP协议发送出去,并在接收端播放出来。其中,AudioFormat 和 DataLine.Info 是用于配置音频输入输出的参数,具体可以根据实际需求进行调整。start() 方法中,发送端通过读取麦克风输入的音频数据,将其存储到 OutputStream 对象中,并通过 Socket 发送出去;接收端通过 ServerSocket 接收连接,获取 InputStream 对象,并将数据写入到音频输出设备中播放。stop() 方法用于停止发送和接收数据。注意,这段代码中没有对数据进行加密和解密,实际应用中需要考虑安全性问题。

UDP是一个无连接的协议,它不提供可靠的数据传输,但是它可以更快地传输数据。在使用UDP传输音频时,你需要将音频数据分割成小的数据包并将其发送到接收方。以下是一个简单的Python示例,演示如何使用UDP传输音频数据: 发送端代码: ```python import socket import pyaudio # 配置音频参数 CHUNK = 1024 FORMAT = pyaudio.paInt16 CHANNELS = 2 RATE = 44100 # 创建UDP套接字 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # 获取本地IP地址 host = socket.gethostname() port = 12345 # 初始化PyAudio p = pyaudio.PyAudio() stream = p.open(format=FORMAT, channels=CHANNELS, rate=RATE, input=True, frames_per_buffer=CHUNK) # 循环发送音频数据 while True: data = stream.read(CHUNK) sock.sendto(data, (host, port)) # 关闭PyAudio stream.stop_stream() stream.close() p.terminate() ``` 接收端代码: ```python import socket import pyaudio # 配置音频参数 CHUNK = 1024 FORMAT = pyaudio.paInt16 CHANNELS = 2 RATE = 44100 # 创建UDP套接字 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # 监听端口 host = socket.gethostname() port = 12345 sock.bind((host, port)) # 初始化PyAudio p = pyaudio.PyAudio() stream = p.open(format=FORMAT, channels=CHANNELS, rate=RATE, output=True, frames_per_buffer=CHUNK) # 循环接收音频数据并播放 while True: data, addr = sock.recvfrom(CHUNK) stream.write(data) # 关闭PyAudio stream.stop_stream() stream.close() p.terminate() ``` 以上代码使用PyAudio库来读取音频数据并将其发送到UDP套接字。接收端从UDP套接字接收数据并播放音频。注意,此代码仅用于演示,实际应用中需要添加错误处理和异常处理。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值