天天看点

【AVFoundation学习】01-AVAudioPlayer使用前言

前言

本系列文章属于个人学习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

继续阅读