2
我嘗試在套接字之間傳遞音頻,但它在客戶端傳遞一次,而不是客戶端停止工作。 我覺得這樣我寫的和發送可能是錯了,請幫我關於這個代碼 以下是我的服務器代碼:如何在java中的套接字之間傳遞音頻
public void run(){
try{
SetInitialSettings();
int bufferSize = (int) format.getSampleRate() * (int) format.getFrameSize();
System.out.println("length :" +bufferSize);
out = new ByteArrayOutputStream();
readagain=true;
while(record){
int count=0;
for(int i=0;i<1000;i++)
{
if(buffer==null){
buffer = new byte[bufferSize];
}
count = line.read(buffer, 0, buffer.length);
if (count > 0) {
//out.write(buffer, 0, count);
//readagain=false;
for (int j=0;i<ser.clientReceiver.audioSender.size();j++){
ser.clientReceiver.audioSender.get(i).cliOut.write("Audio".getBytes());
ser.clientReceiver.audioSender.get(i).cliOut.write('\n');
ser.clientReceiver.audioSender.get(i).cliOut.flush();
ser.clientReceiver.audioSender.get(i).cliOut.write(buffer,0,count);
ser.clientReceiver.audioSender.get(i).cliOut.flush();
Thread.sleep(2000);
}
}
}
}
}
catch(Exception ex)
{
System.out.println(ex.getMessage());
}
}
和下面是我的客戶端代碼:
公共無效的run(){
try{
//audioReceiver = new TAudioReceiver(cli);
//audioReceiver.start();
while(true){
//Thread.sleep(1000);
System.out.println("reading token");
cmd= cli.BufferedReader().readLine();
System.out.println("token :" +cmd);
switch (cmd) {
case "Msg":
message = cli.BufferedReader().readLine();
cmd="None";
break;
case "File":
GetFile();
break;
case "Audio":
PlayAudio();
break;
}
}
//reading msgs here
}
catch(Exception ex)
{
//throw new InterruptedException(ex.getMessage());
}
}
這是功能時,需要從服務器接收到客戶端的「音頻」味精運行
public void PlayAudio()throws Exception{
try{
cli.ServerInputStream().read(buffer);
audio = buffer;
audioIn = new ByteArrayInputStream(audio);
AudioFormat f = new AudioFormat(8000, 8, 1,true, true);
ain= new AudioInputStream(audioIn,f, audio.length/f.getFrameSize());
DataLine.Info info = new DataLine.Info(SourceDataLine.class, f);
try (SourceDataLine line = (SourceDataLine)AudioSystem.getLine(info)) {
int bufferSize = (int) f.getSampleRate()* f.getFrameSize();
buffer= new byte[bufferSize];
int count;
while ((count = ain.read(buffer, 0, buffer.length)) != -1) {
if (count > 0) {
line.write(buffer, 0, count);
}
}
line.drain();
}
}
catch(Exception ex)
{
System.out.println("file" + ex.getMessage());
}
}
請檢查我已替換寫入(緩衝區,0計數) 實際上我正在讀取第二個代碼中的音頻,然後嘗試讀取整個緩衝區。你能告訴我錯誤,我應該在哪裏改變。因爲客戶端是需要接受聊天消息,文件和音頻的一個接收者 –
@ user1998498您仍然無視讀取結果。客戶端副本循環應該是服務器副本循環的反轉,而不是完全不同的一段代碼。如果你擺脫了你不需要的所有額外的協議,兩個循環都是相同的。 – EJP
請看看我的這個問題。現在我得到聲音:http://stackoverflow.com/questions/14489953/receiving-same-java-sound-between-sockets –