Java - Broadcast voice over Java sockets

£可爱£侵袭症+ 提交于 2019-11-30 04:05:29

You split the sound packets into pieces of 1000000 bytes quite randomly and playback these on the client side not taking into account the sample rate and frame size which you calculated on the server side, so you will end up splitting peaces of sound into two which belong together.

You need to decode the same chunks on the server send as you send them on the client side. Maybe it is easier to send them using http multipart (where splitting up data is quite easy) then do it the basic way via sockets. Easiest way to this is to use apache commons http client, have a look here: http://hc.apache.org/httpclient-3.x/methods/multipartpost.html

In addition to HefferWolf's answer, I'd add that you're wasting a lot of bandwidth by sending the audio samples that you read from the microphone. You don't say if your app is restricted to a local network but if you're going over the Internet, it's common to compress/decompress the audio when sending/receiving.

A commonly used compression scheme is the SPEEX codec (a Java implementation is available here), which is relatively easy to use despite the documentation looking a bit scary if you're not familiar with audio sampling/compression.

On the client side, you can use org.xiph.speex.SpeexEncoder to do the encoding:

  • Use SpeexEncoder.init() to initialise an encoder (this will have to match the sample rate, number of channels and endianness of your AudioFormat) and then
  • SpeexEncoder.processData() to encode a frame,
  • SpeexEncoder.getProcessedDataByteSize() and SpeexEncoder.getProcessedData() to get the encoded data

On the client side use org.xiph.speex.SpeexDecoder to decode the frames you receive:

  • SpeexDecoder.init() to initialise the decoder using the same parameters as the encoder,
  • SpeexDecoder.processData() to decode a frame,
  • SpeexDecoder.getProcessedDataByteSize() and SpeexDecoder.getProcessedData() to get the encoded data

There's a bit more involved that I've outlined. E.g., you'll have to spit the data into the correct size for the encoding, which depends on the sample rate, channels and bits per sample, but you'll see a dramatic drop in the number of bytes you're sending over the network.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!