AFNetworking通过JSON从Audio发送字节

时间:2015-08-06 22:39:07

标签: ios objective-c json afnetworking avaudiorecorder

我有客户端iOS应用程序,应该将json请求发送到带有音频字节的服务器。

在服务器上我有Hibernate(MySQL)和下一个型号:

@Column(name = "voice_data", nullable = false, unique = false, columnDefinition="mediumblob")
@Lob
public byte[] getVoiceData() { return voiceData; }
public void setVoiceData(byte[] voiceData) { this.voiceData = voiceData; }

在iOS上,我想获得刚刚录制的语音并保存到DB:

    @property (strong, nonatomic) AVAudioRecorder       *audioRecorder;

    // some code ... 
    NSData *data = [[NSData alloc] initWithContentsOfFile:_audioRecorder.url.path];
    NSString* dataAsString = [NSString stringWithUTF8String:[data bytes]];

    NSDictionary *params = @{
                             MODEL_VOICE_VOICE_DATA : dataAsString,
                             // etc parameters
                             };

    NSString *url = [NSString stringWithFormat:@"%@", URL];        
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

    manager.requestSerializer = [AFJSONRequestSerializer serializer];

    [manager POST:url parameters:params
          success:^(AFHTTPRequestOperation *operation, id responseObject) {
              NSLog(@"%@", responseObject);
          } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
              // ...
          }
     ];
}
//

然后在服务器上我输入了请求数据:

[{"id":13,"voiceData":[],"date":....

所以,看起来它没有正确解析音频(因为它是空的)。我做错了什么?我应该如何将数据发送到服务器?

1 个答案:

答案 0 :(得分:0)

正如@i_am_jorf所提到的,问题在于将二进制数据转换为UTF-8字符串。 解决了QSUtilities library

  1. 下载并链接库到项目(在iOS 8+中需要使用ARC进行一些更新)
  2. 使用encodeBase64WithData函数
  3. 转换数据

    NSData *data = [[NSData alloc] initWithContentsOfFile:_audioRecorder.url.path]; NSString* dataAsString = [QSStrings encodeBase64WithData:data];