Search code examples
iphoneavaudioplayerduration

How to get duration (HH:MM:SS) from AVAudioPlayer in iPhone?


durCurrently i am working in iPhone application, Using AVAudioPlayer to play the audio file in my application, then get the duration value from AVAudioPlayer.

I get the duration value like : 252.765442.

but i want HH/MM/SS 02:52:76.

How to convert this, Please help me

Thanks in Advance..

I tried this:

audioPlayer =  [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:tempFilePath] error:&err];
    [audioPlayer setDelegate:self];
    [audioPlayer prepareToPlay];

    float duration = (float)audioPlayer.duration;
    NSLog(@"duration:%f",duration);

Solution

  • NSTimeInterval theTimeInterval = audioPlayer.duration;
     // Get the system calendar
    NSCalendar *sysCalendar = [NSCalendar currentCalendar];
    
    // Create the NSDates
    NSDate *date1 = [[NSDate alloc] init];
    NSDate *date2 = [[NSDate alloc] initWithTimeInterval:theTimeInterval sinceDate:date1];
    // Get conversion to hours, minutes, seconds
    unsigned int unitFlags = NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
    NSDateComponents *breakdownInfo = [sysCalendar components:unitFlags fromDate:date1  toDate:date2  options:0];
    NSLog(@"%02d:%02d:%02d", [breakdownInfo hour], [breakdownInfo minute], [breakdownInfo second]);
    [date1 release];
    [date2 release];