anon
anon

Reputation:

Convert unsigned char audio to short

Trying to convert an unsigned char to a short. The data is Audio. My system is Little Endian. What I'm doing is this:

    short buf1[audio_size / 2];
    for(size_t i = 0; i < audio_size; i += 2) {
        if(i > audio_size) {
            break;
        }

        if(i + 1 > audio_size) {
            buf1[i] = audio_data[i] << 8;
        } else {
            buf1[i] = audio_data[i] << 8|audio_data[i + 1];
        }
    }

The result is bad audio and EXC_BAD_ACCESS at buf1[i] = info.data[i] << 8|info.data[i + 1];

Update:

Audio sampling rate is 8000. 1 Channel. 16bit PCMU mulaw.

Upvotes: 1

Views: 162

Answers (1)

Olivier Sohn
Olivier Sohn

Reputation: 1322

The buffer has a size audio_size / 2, but you index into it up to the audio_size-1 index so you run into buffer overflow.

You should use i/2 as index instead of i.

Also, another bug in this loop is that

if(i + 1 > audio_size)

should be replaced by

if(i + 1 >= audio_size)

This is another reason for buffer overflow, but this time in the other (source) buffer

Upvotes: 2

Related Questions