SampathKumar
SampathKumar

Reputation: 2545

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);

Upvotes: 2

Views: 5700

Answers (2)

Yoon Lee
Yoon Lee

Reputation: 2039

You can also try,

    // Say you get the duration from AVAudioPlayer *p;
    NSString *dur = [NSString stringWithFormat:@"%02d:%02d", (int)((int)(p.duration)) / 60, (int)((int)(p.duration)) % 60];

As @ Victor John commented, In Swift,

    String(format: "%02d:%02d", ((Int)((audioPlayer?.currentTime)!)) / 60, ((Int)((audioPlayer?.currentTime)!)) % 60)

Upvotes: 8

iDev
iDev

Reputation: 23278

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];

Upvotes: 1

Related Questions