我当时用Java实现了两个程序,一个程序通过UDP发送输出音频,另一个程序接收并播放它。
在执行这两个程序时(它们都通过回送地址进行通信),有时(每10秒)您只能听到一个声音(显然是女人的声音),说“ ciao”。
第一次听到这个消息我很害怕,但是现在我真的很想知道这个音频字节是何时发出的。
%% Generate example cells
c1 = cellfun(@(i) rand(3,4),{1,2,3,4},"UniformOutput",false);
c2 = cellfun(@(i) rand(4,5),{1,2,3},"UniformOutput",false);
c3 = cellfun(@(i) rand(),{1,2,3,4,5,6},"UniformOutput",false);
%% Test 1
temp1 = outerf2(@(a1,a2) a1*a2,c1,c2);
size(temp1)
norm(temp1{2,3}-c1{2}*c2{3})
%% Test 2
% Tensor product
function out = tp(a,b)
da = size(a);
db = size(b);
out = reshape(a(:)*(b(:)'),[da,db]);
endfunction
% Frobenius norm
function out = normf(a)
out = sqrt(sum(a(:).*a(:)));
endfunction
temp2 = outerf3(@(a1,a2,a3) tp(a1,a2)*a3,c1,c2,c3);
size(temp2)
size(temp2{2,3,5})
normf(temp2{2,3,5}-tp(c1{2},c2{3})*c3{5})
public static void main(String args[]) throws Exception {
System.out.println("connect to " + Inet4Address.getLocalHost().toString() + " on port " + port);
DatagramSocket serverSocket = new DatagramSocket(port);
byte[] receiveData = new byte[1280]; //1280!!!!!!
// ( 1280 for 16 000Hz and 3584 for 44 100Hz (use AudioRecord.getMinBufferSize(sampleRate, channelConfig, audioFormat) to get the correct size)
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());
// A thread solve the problem of chunky audio
new Thread(() -> {
toSpeaker(receivePacket.getData());
}).start();
}
}
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.0f);
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();
}
}
答案 0 :(得分:0)
DatagramPacket sendPacket
= new DatagramPacket(buffer, buffer.length, hostAddress, port);
第一个问题在这里。您忽略了长度。应该是:
DatagramPacket sendPacket
= new DatagramPacket(buffer, s, hostAddress, port);
您还忽略了流的结尾。如果s
为-1,则应跳出循环。然后:
ByteArrayInputStream baiss = new ByteArrayInputStream(
receivePacket.getData());
第二个问题在这里。您忽略了长度。应该是:
ByteArrayInputStream baiss = new ByteArrayInputStream(
receivePacket.getData(), receivePacket.getOffset(), receivePacket.getLength());