Search code examples
iphoneobjective-ciosavaudiorecorder

How can i get time of my recorded audio in iphone?


I am recording audio using AVAudioRecorder,and now i want to get exact time duration of my recorded audio,how can i get that.

i have tried this:

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

But my time variable return NULL and durationInSeconds return 'nan',what does that means by nan.

UPDATE

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


Solution

  • If you are using AVAudioPlayer with AVAudioRecorder than you can get the audioPlayer.duration and get the time.

    like this.

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

    But only if you are using AVAudioPlayer with AVAudioRecorder.

    UPDATE

    Or you can do like this.

    //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 becouse their is some microsecond value,and i dont know how to clip it .but thats all.