前言
本系列文章屬于個人學習AVFoundation筆記,本節屬于AVAudioPlayer的使用,使用AVAudioPlayer播放本地音頻檔案
建立音頻播放器
- (AVAudioPlayer *)playerForFile:(NSString *)name {
NSURL *fileURL = [[NSBundle mainBundle] URLForResource:name
withExtension:@"wav"];
NSError *error;
AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL
error:&error];
if (player) {
player.numberOfLoops = -1; // loop indefinitely
player.enableRate = YES;
[player prepareToPlay];
} else {
NSLog(@"Error creating player: %@", [error localizedDescription]);
}
return player;
}
播放控制(開始、暫停、停止)
//播放
- (void)play {
if (!self.playing) {
NSTimeInterval delayTime = [self.audioPlayer deviceCurrentTime] + 0.01;
[self.audioPlayer playAtTime:delayTime];
self.playing = YES;
}
}
//停止
- (void)stop {
if (self.playing) {
[self.audioPlayer stop];
self.audioPlayer.currentTime = 0.0f;
self.playing = NO;
}
}
//暫停
- (void)pause {
if (self.playing) {
[self.audioPlayer pause];
self.playing = NO;
}else{
[self play];
}
}
源碼位址
https://github.com/GeeksChen/AudioPlayer.git