2010-01-18 60 views
3

我有一個問題,我已經設置MediaLocator麥克風輸入,然後創建播放器。 我需要從麥克風中獲取聲音,將其編碼爲質量較低的流,並通過UDP將其作爲數據報包發送。 下面的代碼,我發現大部分的在線和它適用於我的應用程序:如何在java中通過UDP發送音頻流?

public class AudioSender extends Thread { 

private MediaLocator ml = new MediaLocator("javasound://44100"); 
private DatagramSocket socket; 
private boolean transmitting; 
private Player player; 
TargetDataLine mic; 
byte[] buffer; 
private AudioFormat format; 


private DatagramSocket datagramSocket(){ 
    try { 
     return new DatagramSocket(); 
    } catch (SocketException ex) { 
     return null; 
    } 
} 

private void startMic() { 
    try { 
     format = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, 8000.0F, 16, 2, 4, 8000.0F, true); 
     DataLine.Info info = new DataLine.Info(TargetDataLine.class, format); 
     mic = (TargetDataLine) AudioSystem.getLine(info); 
     mic.open(format); 
     mic.start(); 
     buffer = new byte[1024]; 
    } catch (LineUnavailableException ex) { 
     Logger.getLogger(AudioSender.class.getName()).log(Level.SEVERE, null, ex); 
    } 
} 

private Player createPlayer() { 
    try { 
     return Manager.createRealizedPlayer(ml); 
    } catch (IOException ex) { 
     return null; 
    } catch (NoPlayerException ex) { 
     return null; 
    } catch (CannotRealizeException ex) { 
     return null; 
    } 
} 

private void send() { 
    try { 
     mic.read(buffer, 0, 1024); 
     DatagramPacket packet = 
      new DatagramPacket(
       buffer, buffer.length, InetAddress.getByName(Util.getRemoteIP()), 91); 
     socket.send(packet); 
    } catch (IOException ex) { 
     Logger.getLogger(AudioSender.class.getName()).log(Level.SEVERE, null, ex); 
    } 
} 

@Override 
public void run() { 
    player = createPlayer(); 
    player.start(); 
    socket = datagramSocket(); 
    transmitting = true; 
    startMic(); 
    while (transmitting) { 
     send(); 
    } 
} 

public static void main(String[] args) { 
    AudioSender as = new AudioSender(); 
    as.start(); 
} 

}

而且唯一的事情,當我運行接收機類出現這種情況,是我從發送方聽到這個播放器類。 我似乎無法看到TargetDataLine和Player之間的連接。 基本上,我需要獲取聲音表單播放器,並以某種方式將其轉換爲字節[],因此我可以將它作爲數據報發送。 任何想法?一切都可以接受,只要它有效:)

+0

應該使用接收器而不是播放器... – 2012-03-10 21:33:09

回答

2

你不要在這裏什麼Player類,你想用javax.sound.sampled中的類。據我所知,玩家可以播放聲音,而不是訪問其內容。

我還沒有測試過這個,但是嘗試在您創建的TargetDataLine上使用.read來填充緩衝區,然後將緩衝區發送給其他主機。

+0

那麼.read(buffer,0,buffer.size)會填充給定的緩衝區嗎?將嘗試,謝謝:) – 2010-01-18 13:33:55