How can I get the time of my recorded sound in iphone?

I am recording audio using AVAudioRecorder , and now I want to get the exact duration of my recorded sound, how can I get it.

I tried this:

 AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:avAudioRecorder.url options:nil]; CMTime time = asset.duration; double durationInSeconds = CMTimeGetSeconds(time); 

But my variable time returns NULL and durationInSeconds returns 'nan', which means on-line.

UPDATE

user1903074 answer solved my problem, but just for curiosity, is this any way to do this without AVAudioplayer .

+6
source share
3 answers

If you use AVAudioPlayer with AVAudioRecorder , you can get audioPlayer.duration and get the time.

like this.

  NSError *playerError; audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:yoururl error:&playerError]; NSlog(@"%@",audioPlayer.duration); 

But only if you use AVAudioPlayer with AVAudioRecorder .

UPDATE

Or you can do it as follows.

 //put this where you start recording myTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(updateTime) userInfo:nil repeats:YES]; // a method for update - (void)updateTime { if([recorder isRecording]) { float minutes = floor(recorder.currentTime/60); float seconds = recorder.currentTime - (minutes * 60); NSString *time = [[NSString alloc] initWithFormat:@"%0.0f.%0.0f", minutes, seconds]; } } 

steel, you can get some delay because they have a value of a few microseconds, and I don’t know how to fix it. But all this.

+13
source

My solution is simply to keep track of the start date, and in the end to count the elapsed time. It worked for me because the user starts and stops the recorder.

In class recorder

 NSDate* startTime; NSTimeInterval duration; -(void) startRecording { //start the recorder ... duration = 0; startTime = [NSDate date]; } -(void) stopRecording { //stop the recorder ... duration = [[NSDate date] timeIntervalSinceDate:startRecording]; } 
+1
source

I know that the original question was looking for an answer in Objective-C, but for those who want to do this in Swift, this works with Swift 4.0:

 let recorder = // Your instance of an AVAudioRecorder let player = try? AVAudioPlayer(contentsOf: recorder.url) let duration = player?.duration ?? 0.0 

Assuming you have a valid recorder, you will get a duration value that is set as TimeInterval .

0
source

All Articles