从文件获取字节数据 [英] Getting byte Data from File

查看:109
本文介绍了从文件获取字节数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要做什么,我正在尝试将我用AVAudioRecorder录制的音频文件(可能长达一个小时,例如Podcast)上传到我们的后端.除了上载到服务器外,如果用户选择,还需要能够暂停"和恢复".因此,我相信,我需要在NSData类上使用dataWithBytesNoCopy:buffer来实现这一目标.

WHAT IM DOING I am trying to get an audio file (could be up to an hour long. eg. a Podcast) that I've recorded with AVAudioRecorder to be uploaded to our backend. In addition to being uploaded to the server it needs to be able to be "Paused" and "Resumed" if the user chooses. Because of this, I believe, I need to use dataWithBytesNoCopy:buffer on the NSData class to achieve this.

我在哪里,我知道我可以使用传递的self.mediaURL属性来获取数据:

WHERE IM AT I know for a fact I can get the data with using the passed self.mediaURL property:

if (self.mediaURL) {

    NSData *audioData = [NSData dataWithContentsOfURL:self.mediaURL];

    if (audioData) {

        [payloadDic setObject:audioData forKey:@"audioData"];
    }

}

但是,这不会给我所需的功能.我正在尝试跟踪上传的字节,以便在用户暂停时可以恢复.

However, this will not give me the desired functionality. I am trying to keep track of the bytes uploaded so that I can resume if the user pauses.

问题:如何使用提供的self.mediaURL,以便我可以检索文件并能够像本例一样计算字节长度?

QUESTION How can I use the provided self.mediaURL so that I can retrieve the file and be able to calculate the byte length like this example?

Byte *buffer = (Byte*)malloc((long)audioFile.size);
NSUInteger buffered =[rep getBytes:buffer fromOffset:0.0 length:(long)rep.size error:nil];

NSMutableData *body = [[NSMutableData alloc] init];
body = [NSMutableData dataWithBytesNoCopy:buffer length:buffered freeWhenDone:YES];

推荐答案

使用系统提供的功能,而不是通过尝试重新发明轮子使事情变得更复杂. NSURLSession使您可以后台上传 .您将任务交给会话(使用后台会话配置创建),然后走开.如果可以的话,上传会分段进行.无需暂停"或恢复";系统负责一切.您的应用程序甚至不必运行.如果需要身份验证,则将根据需要在后台唤醒您的应用.该体系结构只是针对您所描述的情况而设计的.

Instead of making things more complicated for yourself by trying to reinvent the wheel, use what the system gives you. NSURLSession lets you do a background upload. You hand the task to the session (created using the background session configuration) and just walk away. The upload takes place in pieces, when it can. No "pause" or "resume" needed; the system takes care of everything. Your app doesn't even have to be running. If authentication is needed, your app will be woken up in the background as required. This architecture is just made for the situation you describe.

如果问题是您想要随机访问文件数据,而不必将整个内容读入海量的NSData中,请使用NSFileHandle.

If the problem is that you want random access to file data without having to read the whole thing into a massive NSData, use NSFileHandle.

这篇关于从文件获取字节数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆