我正在使用post方式将音频从iphone发送到wcf服务进行音频传输,然后保存音频,但保存的音频没有播放。
//服务
[OperationContract]
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest, UriTemplate = "Upload/?FileName={FileName}")]
bool Upload(Stream fileStream, string FileName);
//上传音频的方法
public bool Upload(Stream fileStream, string FileName)
{
try
{
string FolderPath = System.AppDomain.CurrentDomain.BaseDirectory + "Audio\\";
if (!Directory.Exists(FolderPath))
{
Directory.CreateDirectory(FolderPath);
}
FileStream fileToupload = new FileStream(FolderPath + FileName, FileMode.Create, FileAccess.Write);
byte[] bytearray = new byte[1000000];
int bytesRead, totalBytesRead = 0;
while ((bytesRead = fileStream.Read(bytearray, 0, bytearray.Length)) > 0)
{
fileToupload.Write(bytearray, 0, bytesRead); // Write directly to the file
totalBytesRead += bytesRead;
}
fileToupload.Close();
fileToupload.Dispose();
return true;
}
catch
{
return false;
}
}
// iPhone代码
-(void)uploadAudioFile{
if([WMUtility isNetConnected]){
NSData *fileData=[NSData dataWithContentsOfURL:soundFileURL];
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:[[NSString stringWithFormat:@"%@/Upload/?FileName=%@",WM_APP_WEBSERVICE_URL,[NSString stringWithFormat:@"eNableMobileAudio_%@.caf",dateTime]] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];
[request setHTTPMethod:@"POST"];
NSString *boundary = @"---------------------------14737809831466499882746641449";
NSMutableData *body = [[NSMutableData alloc]init];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"audioFile\"; filename=\"eNableMobileAudio_%@.caf\"\r\n",dateTime] dataUsingEncoding:NSUTF8StringEncoding]];
//[soundFileURL lastPathComponent]
[body appendData:[@"Content-Transfer-Encoding: binary\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:fileData];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
NSString *contentType = [NSString stringWithFormat:@"application/octet-stream/form-data; boundary=%@",boundary];
[request addValue:contentType forHTTPHeaderField: @"Content-Type"];
NSLog(@"%@",[NSString stringWithUTF8String:[body bytes]]);
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(@"%@",returnString);
}
}