简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM