Search code examples
iphoneobjective-caudioreversensmutabledata

how to reverse order of NSMutableData


I want to reverse bytes of NSMutableData.

I am generating nsmutabledata object from a audio file. and playing it using data. my purpose is play audio reverse.

If I can reverse the NSMutableData I will be success.

Here is my code

NSString *inputVideoPath = [[NSBundle mainBundle] pathForResource:@"chalne" ofType:@"mp3"];

NSMutableData *wave=[NSMutableData dataWithContentsOfURL:[NSURL fileURLWithPath:inputVideoPath]];

avPlayer = [[AVAudioPlayer alloc] initWithData:wave error:nil ];
[avPlayer prepareToPlay];
[avPlayer play];

Solution

  • Simply reversing the order of the bits will not work, because a bytestream of sound data has a specific format. You'll want to reverse the samples, not the bytestream as a whole. However, as to answer 'how to reverse the bytes of an NSData', this ought to work (typed it out, may have typos):

    NSData *myData;
    const char *bytes = [myData bytes];
    char *reverseBytes = malloc(sizeof(char) * [myData length]);
    int index = [myData length] - 1;
    for (int i = 0; i < [myData length]; i++)
        reverseBytes[index--] = bytes[i];
    NSData *reversedData = [NSData dataWithBytes:reverseBytes length:[myData length]]
    free(reverseBytes);