录音获取文件大小
Posted
技术标签:
【中文标题】录音获取文件大小【英文标题】:Audio Recording get file size 【发布时间】:2014-07-08 22:07:03 【问题描述】:我正在使用 AVAudioRecorder 在我的 ios 应用程序中录制某些内容,并且我想以字节为单位获取录制文件的大小。有什么办法可以做到吗?
这是我设置记录器的代码:
NSArray *pathComponents = [NSArray arrayWithObjects:
[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject],
@"MyAudioMemo.m4a",
nil];
outputFileURL = [NSURL fileURLWithPathComponents:pathComponents];
// Setup audio session
AVAudioSession *session = [AVAudioSession sharedInstance];
[session setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
// Define the recorder setting
NSMutableDictionary *recordSetting = [[NSMutableDictionary alloc] init];
[recordSetting setValue:[NSNumber numberWithInt:kAudioFormatMPEG4AAC] forKey:AVFormatIDKey];
[recordSetting setValue:[NSNumber numberWithFloat:44100.0] forKey:AVSampleRateKey];
[recordSetting setValue:[NSNumber numberWithInt: 2] forKey:AVNumberOfChannelsKey];
// Initiate and prepare the recorder
recorder = [[AVAudioRecorder alloc] initWithURL:outputFileURL settings:recordSetting error:nil];
recorder.delegate = self;
recorder.meteringEnabled = YES;
[recorder prepareToRecord];
这是我试图获取文件大小的地方:
- (void) audioRecorderDidFinishRecording:(AVAudioRecorder *)avrecorder successfully:(BOOL)flag
// Convert to NSData
NSData *data = [NSData dataWithContentsOfFile:recorder.url];
// Convert to NSString
NSString* dataAsString = [NSString stringWithUTF8String:[data bytes]];
NSLog(@"Size: %@", dataAsString);
NSLog 不返回任何内容。任何帮助表示赞赏。
【问题讨论】:
【参考方案1】:好的,我想通了,您可以通过以下方式获取文件大小:
unsigned long long size = [[NSFileManager defaultManager] attributesOfItemAtPath:[recorder.url path] error:nil].fileSize;
然后将其转换为字符串:
NSLog(@"This is the file size of the recording in bytes: %llu", size);
【讨论】:
【参考方案2】:Swift 5,我刚刚将它添加到我的 audioRecorderDidFinishRecording 委托函数的末尾:
guard let attributes = try? FileManager.default.attributesOfItem(atPath: url.path) else
print("::: NO FILE SIZE!")
return
if let fileSize = attributes[FileAttributeKey.size] as? Double
let bcf = ByteCountFormatter()
bcf.countStyle = .file
let fileSize64 = Int64(fileSize)
// BYTES:
print("There were \(fileSize) bytes")
// KILOBYTES:
bcf.allowedUnits = [.useKB]
let kbSizeString = bcf.string(fromByteCount: fileSize64)
print("::: FILE SIZE: " + kbSizeString)
// MEGABYTES:
bcf.allowedUnits = [.useMB]
let mbSizeString = bcf.string(fromByteCount: fileSize64)
print("::: FILE SIZE: " + mbSizeString)
【讨论】:
以上是关于录音获取文件大小的主要内容,如果未能解决你的问题,请参考以下文章