为什么要返回负值

时间:2012-03-06 09:39:24

标签: iphone ios ipad avaudioplayer

我想显示目录中的音频文件列表及其持续时间,以便获得我使用的持续时间:

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会返回负值。我想知道为什么,以及如何解决它。

祝你好运

2 个答案:

答案 0 :(得分:2)

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; 

答案 1 :(得分:0)

希望这会对你有所帮助.. 在您的代码中,您在nslog中打印而没有分配和错误的格式,因此它的减去。所以检查一次。

AVAudioPlayer * sound = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL URLWithString:@"/Users/apple/Desktop/LabelTextDemo/LabelTextDemo/song2.caf"] error:nil];

NSLog(@"%@",[NSString stringWithFormat:@"%.2f", sound.duration]);