how to add echo effect on audio file using objective-c

Solutions Collect From Internet About “how to add echo effect on audio file using objective-c”

Echo is pretty simple. You need a delay line, and little multiplication. Assuming one channel and audio already represented in floating point, a delay line would look something like this (in C-like pseudo-code):

int LENGTH = samplerate * seconds; //seconds is the desired length of the delay in seconds
float buffer[ LENGTH ];
int readIndex = 0, writeIndex = LENGTH - 1;

float delayLine.readNext( float x ) {
    float ret = buffer[readIndex];
    ++readIndex;
    if( readIndex >= LENGTH )
        readIndex = 0;
    return ret;
}
void delayLine.writeNext( float x ) {
    buffer[ writeIndex ] = x;
    ++writeIndex;
    if( writeIndex >= LENGTH )
        writeIndex = 0;
}

Don’t forget to initialize the buffer to all zeros.

So that’s your delay line. Basic usage would be this:

float singleDelay( float x ) {
    delayLine.writeNext(x);
    return delayLine.readNext( x );
}

But you won’t hear much difference: it’ll just come out later. If you want to hear a single echo, you’ll need something like this:

float singleEcho( float x, float g ) {
    delayLine.writeNext(x);
    return x + g * delayLine.readNext( x );
}

where g is some constant, usually less than zero.

Now say you want a stream of echos: “HELLO… Hello… hello… h…” like that. You just need to do a bit more work:

float echo( float x, float g ) {
   float ret = x + g * delayLine.readNext( x );
   delayLine.writeNext( ret );
   return ret;
}

Notice how the output of the whole thing is getting fed back into the delay line this time, rather than the input. In this case, it’s very important that |g| < 1.

You may run into issues of denormals here. I can’t recall if that’s an issue on iOS, but I don’t think so.