3

I want to play a specified duration within a sound file on IOS. I found a method in AVAudioPlayer that seeks to the begining of the playing (playAtTime:) but i cannot find a direct way to specify an end time before the end of the sound file.

Is there is a way to achieve this?

cduhn
  • 17,818
  • 4
  • 49
  • 65
Basem Saadawy
  • 1,808
  • 2
  • 20
  • 30

1 Answers1

12

If you don't need much precision and you want to stick with AVAudioPlayer, this is one option:

- (void)playAtTime:(NSTimeInterval)time withDuration:(NSTimeInterval)duration {
    NSTimeInterval shortStartDelay = 0.01;
    NSTimeInterval now = player.deviceCurrentTime;

    [self.audioPlayer playAtTime:now + shortStartDelay];
    self.stopTimer = [NSTimer scheduledTimerWithTimeInterval:shortStartDelay + duration 
                                                      target:self 
                                                    selector:@selector(stopPlaying:)
                                                    userInfo:nil
                                                     repeats:NO];
}

- (void)stopPlaying:(NSTimer *)theTimer {
    [self.audioPlayer pause];
}

Bear in mind that stopTimer will fire on the thread's run loop, so there will be some variability in how long the audio plays, depending on what else the app is doing at the time. If you need a higher level of precision, consider using AVPlayer instead of AVAudioPlayer. AVPlayer plays AVPlayerItem objects, which let you specify a forwardPlaybackEndTime.

cduhn
  • 17,818
  • 4
  • 49
  • 65
  • 1
    Thanks for AVPlayer. I did not know about it before. – Basem Saadawy Jul 05 '11 at 07:20
  • @cduhn what would you use, to loop a sound that's f.e. 10 seconds long, but want to keep it playing for f.e. one minute? – Georg Oct 19 '18 at 09:18
  • Wow! Using an audio version of AVPlayer has serious advantages over AVAudioPlayer, especially for stopping play at a particular time. Thanks. – bpedit Nov 20 '21 at 19:42