问题
I wonder if there is a more elegant way to play a mp3 file with AVAudioPlayer Class, from t1 to t2 time without using NSTimers?
回答1:
AVAudioPlayer has a method playAtTime: which takes care of t1, however there's no easy way to stop playing at a specific time (t2).
As of iOS8 AVFoundation has new api's such as AVAudioEngine and AVAudioPlayerNode. You may find implementing AVAudioPlayerNode instead is more suited for your requirements as it has a method named
- scheduleSegment:startingFrame:frameCount:atTime:completionHandler:
which is for playing a segment of an audio file.
回答2:
I tested below code and it works perfect within t1 and t2 time. But don't forget to define AVAudioEngine *engine in your class.
- (void) playAudioWithinT1: (float) t1 andT2:(float) t2{
//t1 and t2 are the seconds to play audio in between
NSError *error;
NSURL *urlForSoundFile;
float startingFrame;
float framesToPlay;
NSString *audioPath = [[NSBundle mainBundle] pathForResource:@"_preview" ofType:@"mp3"];
urlForSoundFile = [NSURL fileURLWithPath:audioPath];
engine = [[AVAudioEngine alloc] init];
AVAudioPlayerNode *player = [[AVAudioPlayerNode alloc] init];
[engine attachNode:player];
AVAudioFile *file = [[AVAudioFile alloc] initForReading:urlForSoundFile
error:&error];
startingFrame = (t1 * file.processingFormat.sampleRate);
framesToPlay = (t2 * file.processingFormat.sampleRate - startingFrame);
AVAudioMixerNode *mainMixer = [engine mainMixerNode];
[engine connect:player to:mainMixer format:file.processingFormat];
[player scheduleSegment:file startingFrame:startingFrame frameCount:framesToPlay atTime:nil completionHandler:nil];
[engine startAndReturnError:&error];
[player play];
}
来源:https://stackoverflow.com/questions/33989202/how-to-play-an-mp3-file-in-xcode-from-time-t1-to-t2-with-avaudioplayer