How to play an mp3 file in Xcode from time t1 to t2 with AVAudioPlayer

女生的网名这么多〃 提交于 2019-12-13 09:09:20

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!