【问题标题】:Read continues audio stream from socket从套接字读取继续音频流
【发布时间】:2015-08-29 21:35:02
【问题描述】:

我正在制作一个应用程序,我需要在其中读取以字节数组形式发送的连续声音流。服务器端记录听起来像这样(基于 SO 上的示例):

    // Get the minimum buffer size required for the successful creation of an AudioRecord object.
    int bufferSizeInBytes = AudioRecord.getMinBufferSize(RECORDER_SAMPLERATE, RECORDER_CHANNELS,
            RECORDER_AUDIO_ENCODING);
    bufferSizeInBytes = 30000;

    // Initialize Audio Recorder.
    _audio_recorder = new AudioRecord(MediaRecorder.AudioSource.MIC, RECORDER_SAMPLERATE,
            RECORDER_CHANNELS, RECORDER_AUDIO_ENCODING, bufferSizeInBytes);

    // Start Recording.
    _audio_recorder.startRecording();

    int numberOfReadBytes = 0;
    byte audioBuffer[] = new byte[bufferSizeInBytes];
    boolean recording = false;
    float tempFloatBuffer[] = new float[3];
    int tempIndex = 0;
    byte totalByteBuffer[] = new byte[60 * 44100 * 2];
while (true)
{
    float totalAbsValue = 0.0f;
    short sample = 0;

    numberOfReadBytes = _audio_recorder.read(audioBuffer, 0, bufferSizeInBytes);

    for (int i = 0; i < bufferSizeInBytes; i += 2)
    {
        sample = (short) ((audioBuffer[i]) | audioBuffer[i + 1] << 8);
        totalAbsValue += Math.abs(sample) / (numberOfReadBytes / 2);
    }

    tempFloatBuffer[tempIndex % 3] = totalAbsValue;
    float temp = 0.0f;

    for (int i = 0; i < 3; ++i)
        temp += tempFloatBuffer[i];

    if ((temp >= 0 && temp <= _sensitivity) && recording == false)
    {
        Log.i("TAG", "1");
        tempIndex++;
        continue;
    }

    if (temp > _sensitivity && recording == false)
    {
        Log.i("TAG", "2");
        recording = true;
    }

    if(temp < _sensitivity && recording == true)
    {
        recording = false;
        continue;
    }

    for (int i = 0; i < numberOfReadBytes; i++)
        totalByteBuffer[i] = audioBuffer[i];

    if (prepare_sound(totalByteBuffer, numberOfReadBytes))
    {
        totalByteBuffer = new byte[60 * 44100 * 2];

        tempIndex++;
    }
}

这个例子是录制声音并在没有更多声音要录制时将其保存到文件中。另一方面,我的目标是在有声音时录制声音,并在仍在录制时即时发送此声音。因此,我想以一种正确的方式发送声音,而不是在没有声音要录制时将其存储到文件中。到目前为止,我正在获取带有数据的 byte[] 并将其存储在一个对象中,然后使用 ObjectOutputStream 将其发送给客户端。然后客户端将创建一个临时声音文件并使用 MediaPlayer 播放它。但我觉得这不是实现我的目标最有效的方式。那么,由于媒体播放器不支持播放纯字节 [] 数据,有没有更有效的方法来发送连续的数据流?

感谢您的帮助和提示!

【问题讨论】:

    标签: android sockets bluetooth stream


    【解决方案1】:

    发现对我来说最好的解决方案是录制声音,当缓冲区已满时将其发送到客户端。然后客户端使用 AudioTrack 实例来播放包含如下数据的 byte[]:

    public void onSoundReceived(byte[] sound)
    {
        _audio_input_stream.write(sound, 0, sound.length);
    }
    

    这也使声音更加“不滞后”,因为它不是一个 MediaPlayer 实例,它会在每次播放完数据后停止声音。

    【讨论】:

      猜你喜欢
      • 2012-02-16
      • 1970-01-01
      • 2014-02-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-20
      • 2020-10-20
      • 1970-01-01
      相关资源
      最近更新 更多