Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-c/IOS: What's the simplest way to play an audio file backwards

I've been struggling with this one for quite a while now, and there are no code examples of it being done on the net. Can anyone help me?

My app uses AVFoundation to record the audio. @16 bit depth , 2 channels , WAV

I can access the bytes of the audio, I just don't know how to reverse it.

like image 920
DaveSmith122 Avatar asked Sep 10 '11 19:09

DaveSmith122


1 Answers

In wave data samples are interleaved. This means the data is organised like this.

Sample 1 Left | Sample 1 Right | Sample 2 Left | Sample 2 right ... Sample n Left | Sample n right

As each sample is 16-bits (2 bytes) the first 2 channel sample (ie for both left and right) is 4 bytes in size.

This way you know that the last sample in a block of wave data is as follows:

wavDataSize - 4

You can then load each sample at a time by copying it into a different buffer by starting at the end of the recording and reading backwards. When you get to the start of the wave data you have reversed the wave data and playing will be reversed.

Edit: If you want easy ways to read wave files on iOS check out the Audio File Services Reference.

Edit 2:

readPoint  = waveDataSize;
writePoint = 0;
while( readPoint > 0 )
{
    readPoint -= 4;
    Uint32 bytesToRead = 4;
    Uint32 sample;
    AudioFileReadBytes( inFile, false, maxData, &bytesToRead &sample );
    AudioFileWriteBytes( outFile, false, writePoint, &bytesToRead, &sample );

    writePoint += 4;
}
like image 184
Goz Avatar answered Oct 12 '22 20:10

Goz