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

2019-04-07 00:04发布

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.

3条回答
smile是对你的礼貌
2楼-- · 2019-04-07 00:28

I know the original question was looking for an answer in Objective-C, but for those looking to do so 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, then you will get a duration value, which is given as a TimeInterval.

查看更多
太酷不给撩
3楼-- · 2019-04-07 00:33

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.

查看更多
Explosion°爆炸
4楼-- · 2019-04-07 00:34

My solution is simply to keep track of the start date, and at the end, calculate the time passed. It worked for me because the user is starting and stopping the recorder.

In the recorder class

NSDate* startTime;
NSTimeInterval duration;

-(void) startRecording
{
   //start the recorder
   ...
   duration = 0;
   startTime = [NSDate date];

}

-(void) stopRecording
{
   //stop the recorder
   ...
   duration = [[NSDate date] timeIntervalSinceDate:startRecording];
}
查看更多
登录 后发表回答