如何使用 AVAudioPlayer 从时间 t1 到 t2 播放 Xcode 中的 mp3 文件
How to play an mp3 file in Xcode from time t1 to t2 with AVAudioPlayer
我想知道是否有更优雅的方式来使用 AVAudioPlayer Class 从 t1 到 t2 时间不使用 NSTimers 播放 mp3 文件?
AVAudioPlayer 有一个方法 playAtTime:
负责 t1,但是没有简单的方法来停止播放具体时间(t2).
截至 iOS8 AVFoundation 有新的 api,例如 AVAudioEngine 和 AVAudioPlayerNode。您可能会发现实施 AVAudioPlayerNode 更适合您的要求,因为它有一个名为
的方法
- scheduleSegment:startingFrame:frameCount:atTime:completionHandler:
用于播放一段音频文件。
我测试了下面的代码,它在 t1 和 t2 时间内运行良好。但是不要忘记在 class.
中定义 AVAudioEngine *engine
- (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];
}
我想知道是否有更优雅的方式来使用 AVAudioPlayer Class 从 t1 到 t2 时间不使用 NSTimers 播放 mp3 文件?
AVAudioPlayer 有一个方法 playAtTime:
负责 t1,但是没有简单的方法来停止播放具体时间(t2).
截至 iOS8 AVFoundation 有新的 api,例如 AVAudioEngine 和 AVAudioPlayerNode。您可能会发现实施 AVAudioPlayerNode 更适合您的要求,因为它有一个名为
的方法- scheduleSegment:startingFrame:frameCount:atTime:completionHandler:
用于播放一段音频文件。
我测试了下面的代码,它在 t1 和 t2 时间内运行良好。但是不要忘记在 class.
中定义AVAudioEngine *engine
- (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];
}