DavidNg
DavidNg

Reputation: 2836

iOS: play audio file at a specific time and stop after a specific duration

I have an audio file with length of 500 miniseconds for my app. I want app users to play the audio at minisecond 100 (by pressing a button) and the audio will automatically stops at minisecond 150. This is a code that I have done so far:

    AVAudioPlayer *audioPlayer = [[[AVAudioPlayer alloc]
                   initWithContentsOfURL:[NSURL fileURLWithPath:filePath]
                   error:nil] autorelease];
    [audioPlayer setCurrentTime:100.00f];
    [audioPlayer play];

Would you please help me with the stopping part? Thank you

Upvotes: 0

Views: 2264

Answers (1)

Matt
Matt

Reputation: 1586

You could create an instance of NSTimer with the desired play interval, then when the timer fires, stop audio. Create the timer on the main thread, and in a place in your code in an applicable area where you can get a reference for the audioPlayer. Make sure you handle interruptions, IE, User pauses or stops audio somehow, or if the audioPlayer is deallocated somewhere, your app goes into the background, or whatever else you need to handle, by invalidating and disposing of the timer. See the docs for information on NSTimer. http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/nstimer_Class/Reference/NSTimer.html

Upvotes: 2

Related Questions