首页 > 解决方案 > 如何将 AVAudioRecorder 给出的数据重新解释为 const char *?

问题描述

问题:

我要解决的问题如下。我有 AVAudioRecorder 录制的音频数据。我可以通过以下方式获取 NSData:

NSData *data = [NSData dataWithContentsOfURL: self.audioRecorder.url];

但是然后我需要将此 NSData 转换/重新解释为 const char* 形式,它基本上看起来像

00 01 00 ff 

这是十六进制的字节或至少是等效的字符串。它们实际上不必是十六进制的,只需要可转换为十六进制即可。

问题:

我的问题是 NSData 中有“\0”。所以如果我做这样的事情:

    NSUInteger len = [data length];
    Byte *byteData = (Byte*)malloc(len);
    memcpy(byteData, [data bytes], len);

它不会起作用,因为当它遇到第一个“\0”时数据将被截断。我对音频文件非常陌生,但我认为这是因为标题中的 x00 值。所以基本上,我不希望它们被解释为“\0”而是“00”。有没有办法做到这一点?

标签: iosobjective-cstringdata-conversionavaudiorecorder

解决方案


不确定我是否理解这个问题或你想要做什么。您memcpy会将所有字节复制到byteData缓冲区,只有当您尝试将 byteData 缓冲区用作字符串 ( char*) 并将它们传递给格式函数 ( NSLog(%"%s", val)) 时,它才会被切断。如果您想要将数据的字符串表示为十六进制:

NSString* bytesToHex(Byte* bytes, NSUInteger count) {
    NSMutableString *hex = [NSMutableString string];
    for(int i = 0; i < count; i++) [hex appendFormat:@"%.2x " , *(bytes+i)];
    return hex;
}

NSString* dataToHex(NSData* data) {
    return bytesToHex((Byte*)data.bytes, data.length);
}

会做到的,即:

Byte* bytes = (Byte*)"t\0h\0i\0s\0 i\0s\0 a\0 t\0e\0st";
NSData* data = [NSData dataWithBytes:bytes length:24];

NSLog(@"%@",NSLog(@"%@", dataToHex(data));

将打印:

74 00 68 00 69 00 73 00 20 69 00 73 00 20 61 00 20 74 00 65 00 73 74 00

或者

Byte* bytes = (Byte*)"t\0h\0i\0s\0 i\0s\0 a\0 t\0e\0st";
NSData* data = [NSData dataWithBytes:bytes length:24];
NSUInteger len = [data length];
Byte *byteData = (Byte*)malloc(len);
memcpy(byteData, [data bytes], len);
NSLog(@"%@", bytesToHex(byteData, len));

将打印:

74 00 68 00 69 00 73 00 20 69 00 73 00 20 61 00 20 74 00 65 00 73 74 00

刚想起一件事

更简单的是,如果您使用 NSData 描述属性,它已经为您提供了十六进制数据!

Byte* bytes = (Byte*)"t\0h\0i\0s\0 i\0s\0 a\0 t\0e\0st";
NSData* data = [NSData dataWithBytes:bytes length:24];

NSLog(@"%@", data.description);

将打印

<74006800 69007300 20690073 00206100 20740065 00737400>

没有那么漂亮,但一样的东西......


推荐阅读