将音频数据上载到服务器

时间:2012-05-28 01:56:57

标签: iphone objective-c http-post audiotoolbox

我正在尝试通过POST请求将音频数据从iphone发送到服务器。 我不想使用文件,而是直接将数据发送到服务器。 我使用AudioToolbox从麦克风获取数据到缓冲区,然后我将此缓冲区发送到服务器。数据已正确接收,服务器创建一个wave文件...但即使此文件不为空,也无法播放声音......如果文件的持续时间太短......

这是回调函数的代码,它发送帖子请求:

void AudioInputCallback(
                    void *inUserData,
                    AudioQueueRef inAQ,
                    AudioQueueBufferRef inBuffer,
                    const AudioTimeStamp *inStartTime,
                    UInt32 inNumberPacketDescriptions,
                    const AudioStreamPacketDescription *inPacketDescs) {

RecordState* recordState = (RecordState*)inUserData;    



    // setting up the URL to post to
    NSString *urlString = @"http://localhost/script/upload.php";


    // setting up the request object now
    NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
    [request setURL:[NSURL URLWithString:urlString]];
    [request setHTTPMethod:@"POST"];

    NSString *boundary = [NSString stringWithString:@"---------------------------14737809831466499882746641449"];
    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
    [request addValue:contentType forHTTPHeaderField: @"Content-Type"];

    /*
     now lets create the body of the post
     */
    NSMutableData *body = [NSMutableData data];
    [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];

    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"userfile\"; filename=\"test.wav\"\r\n",i] dataUsingEncoding:NSUTF8StringEncoding]];


    [body appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];  //NSUTF8StringEncoding

    [body appendData:[NSData dataWithBytes:inBuffer->mAudioData length:inBuffer->mAudioDataByteSize]];

    [body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    // setting the body of the post to the reqeust
    [request setHTTPBody:body];

    // now lets make the connection to the web
    NSHTTPURLResponse *response = nil;
    NSError * error = nil;

    NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

    NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];

    AudioQueueStop(recordState->queue, true);

    AudioQueueFreeBuffer(recordState->queue,
                         recordState->buffers[0]);


    AudioQueueDispose(recordState->queue, true);

}

0 个答案:

没有答案