Попытка потока аудио из моего приложения iOS на сервер nodejs, WAV-файл никогда не откроется.streaming wav от объектива C до nodejs
Я не уверен, что мне не хватает, мне нужно добавить некоторые метаданные в .wav-файл, чтобы аудио-плеер мог его открыть?
Я искал часы, не уверен, где моя проблема, любые указатели помогут.
var util = require('util'),
http = require('http'),
httpProxy = require('http-proxy');
fs = require('fs');
var wstream = fs.createWriteStream('audio.wav');
http.createServer(function (req, res) {
req.on('data', function (chunk) {
wstream.write(chunk);
});
req.on('end', function() {
wstream.end();
console.log("file saved");
res.writeHead(200);res.write("OK");res.end();
});
}).listen(9000);
Objective C:
-(BOOL)startRequestWithContext:(NSMutableDictionary *)context {
requestEnding = NO;
NSString* token = [[WITState sharedInstance] accessToken];
// CF wiring
CFWriteStreamRef writeStream;
CFReadStreamRef readStream;
readStream = NULL;
writeStream = NULL;
CFStreamCreateBoundPair(NULL, &readStream, &writeStream, 65536);
// convert to NSStream and set as property
inStream = CFBridgingRelease(readStream);
outStream = CFBridgingRelease(writeStream);
[outStream setDelegate:self];
[outStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[outStream open];
NSString* urlString;
urlString = kWitSpeechURL;
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]];
[req setHTTPMethod:@"POST"];
[req setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[req setTimeoutInterval:15.0];
[req setHTTPBodyStream:inStream];
[req setValue:[NSString stringWithFormat:@"Bearer %@", token] forHTTPHeaderField:@"Authorization"];
[req setValue:@"wit/ios" forHTTPHeaderField:@"Content-type"];
[req setValue:@"chunked" forHTTPHeaderField:@"Transfer-encoding"];
[req setValue:@"application/json" forHTTPHeaderField:@"Accept"];
// send HTTP request
[NSURLConnection sendAsynchronousRequest:req queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
NSError *serializationError;
NSDictionary *object = [NSJSONSerialization JSONObjectWithData:data options:0 error:&serializationError];
[self.delegate gotResponse:object error:nil];
}];
return YES;
}
-(void)sendChunk:(NSData*)chunk {
debug(@"Adding operation %u bytes", (unsigned int)[chunk length]);
[q addOperationWithBlock:^{
if (outStream) {
[q setSuspended:YES];
debug(@"Uploading %u bytes", (unsigned int)[chunk length]);
[outStream write:[chunk bytes] maxLength:[chunk length]];
}
NSUInteger cnt = q.operationCount;
debug(@"Operation count: %d", cnt);
if (requestEnding && cnt <= 1) {
[self cleanUp];
}
}];
}
-(void)recorderGotChunk:(NSData*)chunk {
dispatch_async(dispatch_get_main_queue(), ^{
if(self.isUploading) {
[self.uploader sendChunk:chunk];
} else {
//not uploading, so save the chunk to the buffer and remove old chunk
if ([self.dataBuffer count] >= self.buffersToSave){
//if we have enough entries, remove the oldest one
[self.dataBuffer removeObjectAtIndex:0];
}
//enqueue the new data
[self.dataBuffer addObject:chunk];
}
[self.delegate recordingSessionRecorderGotChunk:chunk];
});
}
Вам также нужно показать нам сторону iOS. Обратите внимание, что в вашем коде выше вы создаете один поток записи, затем записываете его и закрываете. Вероятно, вы захотите открыть файл (другой), если вместо этого вы получите новый запрос. – jcaron
@ jcaron Да, я понимаю, что я просто хочу получить простейший пример работы, тогда я бы работал над управлением несколькими запросами – bubakazouba
По-прежнему нужна сторона iOS, хотя ... – jcaron