为啥返回负值
Posted
技术标签:
【中文标题】为啥返回负值【英文标题】:why return negative values为什么返回负值 【发布时间】:2012-03-06 09:39:23 【问题描述】:我想显示目录中的音频文件列表及其持续时间,因此要获取我使用的持续时间:
AVAudioPlayer * sound = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:nil];
NSLog([NSString stringWithFormat:@"%f", sound.duration]);
cell.detailTextLabel.text =[NSString stringWithFormat:@"Duration: %.2f sec", sound.duration];
但有时sound.duration
返回一个负值。我想知道为什么,以及如何解决。
最好的问候
【问题讨论】:
【参考方案1】:AudioFileID audioFile;
CFDictionaryRef piDict = nil;
UInt32 piDataSize = sizeof( piDict );
if (noErr != AudioFileOpenURL((CFURLRef)[NSURL fileURLWithPath:filePath], 0x01, kAudioFileCAFType, &audioFile))
return [NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithString:filePath], @"FilePath", @"Unknown",@"Title",@"Unknown",@"Album",@"Unknown",@"Artist",@"0", @"Duration", nil];
if( noErr != AudioFileGetProperty( audioFile, kAudioFilePropertyInfoDictionary, &piDataSize, &piDict ))
AudioFileClose(audioFile);
return [NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithString:filePath], @"FilePath", @"Unknown",@"Title",@"Unknown",@"Album",@"Unknown",@"Artist",@"0", @"Duration", nil];
AudioFileClose(audioFile);
if(piDict)
NSString * duration = @"0";
CFStringRef durationString = nil;
if ( piDict && CFDictionaryGetValueIfPresent(piDict, CFSTR(kAFInfoDictionary_ApproximateDurationInSeconds), (const void **) &durationString))
duration = (NSString*)durationString;
duration = [duration stringByReplacingOccurrencesOfString:@"," withString:@""];
if (duration)
[songInfomationDictionary setObject:duration forKey:@"Duration"];
CFRelease(piDict);
//get duration as string
return nil;
【讨论】:
很高兴添加一点解释以及代码墙【参考方案2】:希望这会对你有所帮助.. 在您的代码中,您在 nslog 中打印而没有分配和错误的格式,因此它的减号。所以检查一次。
AVAudioPlayer * sound = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL URLWithString:@"/Users/apple/Desktop/LabelTextDemo/LabelTextDemo/song2.caf"] error:nil];
NSLog(@"%@",[NSString stringWithFormat:@"%.2f", sound.duration]);
【讨论】:
这一行的问题 cell.detailTextLabel.text =[NSString stringWithFormat:@"Duration: %.2f sec", sound.duration]; lblLabel2.text=[NSString stringWithFormat:@"%.2f", sound.duration];我正在这样做及其工作以上是关于为啥返回负值的主要内容,如果未能解决你的问题,请参考以下文章