how to reverse order of NSMutableData
-
24-06-2021 - |
문제
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];
해결책
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);
다른 팁
I fixed the above example and tested it. now it can be used in a category:
- (NSData*) reversedData
{
NSData *myData = self;
const char *bytes = [myData bytes];
NSUInteger datalength = [myData length];
char *reverseBytes = malloc(sizeof(char) * datalength);
NSUInteger index = datalength - 1;
for (int i = 0; i < datalength; i++)
reverseBytes[index--] = bytes[i];
NSData *reversedData = [NSData dataWithBytesNoCopy:reverseBytes length: datalength freeWhenDone:YES];
return reversedData;
}
-(NSData *)reverseData
{
NSMutableData *data = [[NSMutableData alloc] init];
for(int i = (int)self.length - 1; i >=0; i--){
[data appendBytes: &self.bytes[i] length:1];
}
return [data copy];
}
제휴하지 않습니다 StackOverflow