上传音频 - HTTP流(Upload audio - http streaming)

2019-07-29 08:38发布

我想上传HTTP下的线性文件流模式。 我们的想法是这样做同时几步之遥,1)线索1:录制音频文件并将其存储在一个临时文件2)主题2:取N从临时文件的字节,并将其发送到HTTP服务器。

我怎么能写在HTTP流?在CFHTTPStream我没有看到写的方法,只读:■我需要使用套接字? 谢谢!!!

我实际的代码

   CFWriteStreamRef stream;
   NSString *strUrl = @"myurl";       
   NSURL *url = [[[NSURL alloc] initWithString:strUrl] retain];

   CFStringRef requestMethod = CFSTR("GET");

   CFHTTPMessageRef message= CFHTTPMessageCreateRequest(kCFAllocatorDefault, requestMethod, (CFURLRef)url, kCFHTTPVersion1_1);

    CFHTTPMessageSetHeaderFieldValue(message, CFSTR("Content-Type"),
                                     CFSTR("multipart/form-data"));
   stream =  ??  //CFReadStreamCreateForHTTPRequest(NULL, message);
    CFRelease(message);
  //other headers...        
    if (CFWriteStreamSetProperty(stream, kCFStreamPropertyHTTPShouldAutoredirect, kCFBooleanTrue)  == false)
    {
        NSLog(@"Error");
        return NO;
    }


    //
    // Open the stream
    //
    if (!CFWriteStreamOpen(stream))
    {
        CFRelease(stream);
        NSLog(@"Error");
        return NO;
    }

    CFStreamClientContext context = {0, self, NULL, NULL, NULL};
    CFWriteStreamSetClient(stram, kCFStreamEventHasBytesAvailable | kCFStreamEventErrorOccurred | kCFStreamEventEndEncountered,
                           RSWriteStreamCallBack,
                           &context);
    CFWriteStreamScheduleWithRunLoop(stream, CFRunLoopGetCurrent(), kCFRunLoopCommonModes);

Answer 1:

该解决方案是创建NSInputStream的子类,并实现方法打开,关闭,读,hasBytesAvailable不要忘记 - (NSStreamStatus)流状态。 最后一种方法是从HTTP调用知道,如果我们打开,关闭或我们结束了(NSStreamStatusAtEnd)发送(还有其他的状态,但是这是最重要的)。 我喜欢用一个缓冲tmp文件,因为我要发送大量的数据,但是,也许,数据存储缓冲区可能会更好。 最后,我实现其他类的地方使用个性化的NSInputStream,这里是代码:

    NSURL *url = [NSURL URLWithString:@"url"];
    NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
    [req setHTTPMethod:@"POST"];
    //set headers if you have to do for example: 
    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data"];
    [req setValue:contentType forHTTPHeaderField:@"Content-Type"];
    //Create your own InputStream
    instream = [[CustomStream alloc] init];
    [req setHTTPBodyStream:instream];
    //I remove instream later 
      NSURLConnection *aConnection = [[NSURLConnection alloc] initWithRequest:req delegate:self startImmediately:NO];
    [aConnection scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
    [aConnection start]; 


文章来源: Upload audio - http streaming