AVFoundation(一)---AVAudioPlayer

AVAudioPlayer相当于一个播放器,它支持多种音频格式,而且能够进行进度、音量、播放速度等控制。

下边通过代码来看一下,它的属性和常用方法(具体说明都写在了注释中):

    //AVAudioPlayer使用比较简单
    /*
        1.初始化AVAudioPlayer对象
        这里有两种init方法可以初始化AVAudioPlayer对象
        1)- (instancetype)initWithContentsOfURL:(NSURL *)url error:(NSError **)outError
            使用文件URL初始化播放器,注意这个URL不能是HTTP URL,AVAudioPlayer不支持加载网络媒体流,只能播放本地文件
        2)- (instancetype)initWithData:(NSData *)data error:(NSError **)outError
            使用NSData初始化播放器,注意使用此方法时必须文件格式和文件后缀一致,否则出错,所以相比此方法更推荐使用上述方法或- (instancetype)initWithData:(NSData *)data fileTypeHint:(NSString *)utiString error:(NSError **)outError方法进行初始化
     */
    NSString *path = [[NSBundle mainBundle] pathForResource:@"1" ofType:@"mp3"];
    NSError *error;
    AVAudioPlayer *audioplayer = [[AVAudioPlayer alloc]initWithContentsOfURL:[NSURL URLWithString:path]  error:&error];

    /**
        AVAudioPlayer对象的常见属性
     */
    //.playing 是否正在播放,readonly
    BOOL isPlaying = audioplayer.playing;
    //.numberOfChannels 音频声道数,readonly
    BOOL numberofChannels = audioplayer.numberOfChannels;
    //.duration 音频时长,readonly
    NSTimeInterval MusicDuration = audioplayer.duration;
    //.url 音频文件的路径 readonly
    NSURL *MusicUrl = audioplayer.url;
    //.data 音频数据 readonly
    NSData *MusicData = audioplayer.data;
    //.pan 立体声平衡 如果为-1.0则完全左声道,如果0.0则左右声道平衡,如果为1.0则完全为右声道
    audioplayer.pan = 0.0;
    //.volume 音量大小,范围0-1.0
    audioplayer.volume = 0.5;
    //.enableRate 是否允许改变播放速率
    //播放速率,范围0.5-2.0,如果为1.0则正常播放,如果要修改播放速率则必须设置enableRate为YES
    audioplayer.enableRate = YES;
    audioplayer.rate = 1.0;
    //.currentTime 当前播放时长
    NSTimeInterval MusicCurrentTime = audioplayer.currentTime;
    //.deviceCurrentTime 输出设备播放音频的时间
    NSTimeInterval deviceCurrentTime = audioplayer.deviceCurrentTime;
    //.numberOfLoops 循环播放次数,如果为0则不循环,如果小于0则无限循环,大于0则表示循环次数
    audioplayer.numberOfLoops = 0;
    //音频播放设置信息,只读
    NSDictionary *settingDic = audioplayer.settings;
    
    /**
     *  对象方法
     */
    //- (BOOL)prepareToPlay;     加载音频文件到缓冲区,注意即使在播放之前音频文件没有加载到缓冲区程序也会隐式调用此方法。
    [audioplayer prepareToPlay];
    //- (BOOL)play;     播放音频文件
    [audioplayer play];
    //- (BOOL)playAtTime:(NSTimeInterval)time     在指定的时间开始播放音频
    [audioplayer playAtTime:10];
    //- (void)pause;     暂停播放
    [audioplayer pause];
    //- (void)stop;     停止播放
    [audioplayer stop];
    //@property(nonatomic, copy) NSArray *channelAssignments     获得或设置播放声道
    NSArray *channelArr = audioplayer.channelAssignments;
    
    /**
        代理方法
     
     *  - (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
            //音频播放完成
     
        - (void)audioPlayerDecodeErrorDidOccur:(AVAudioPlayer *)player error:(NSError *)error
            //音频解码发生错误
     */

上边代码就是AVAudioPlayer的简单介绍,接下来,直接上代码,看一下一个简单的音乐播放的实现,可播放、暂停。

@interface ViewController ()<AVAudioPlayerDelegate>
- (IBAction)clickplay:(id)sender;
- (IBAction)clickpause:(id)sender;
@property (weak, nonatomic) IBOutlet UIProgressView *progress;

@property (strong,nonatomic) AVAudioPlayer *audioPlayer;//播放器

@property (weak,nonatomic) NSTimer *timer;//进度更新定时器

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

/**
 *  设置定时器,每0.5秒,更新一次播放进度条
 *
 *  @return timer
 */
-(NSTimer *)timer{
    if (!_timer) {
        _timer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(updateProgress) userInfo:nil repeats:YES];
    }
    return _timer;
}

-(void)updateProgress{
    NSLog(@"updateProgress");
    float progress = self.audioPlayer.currentTime / self.audioPlayer.duration;
    self.progress.progress = progress;
}

/**
 *  创建播放器
 *
 *  @return 音频播放器
 */
-(AVAudioPlayer *)audioPlayer{
    if (!_audioPlayer) {
        NSString *urlStr = [[NSBundle mainBundle]pathForResource:@"1" ofType:@"mp3"];
        NSURL *url = [NSURL URLWithString:urlStr];
        NSError *error = nil;
        //初始化播放器,这里的url只支持文件路径,不支持HTTP url
        _audioPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:url error:&error];
        //设置播放器属性
        _audioPlayer.numberOfLoops = 0;//设置为0表示不循环
        _audioPlayer.delegate = self;
        [_audioPlayer prepareToPlay];
        if (error) {
            NSLog(@"初始化播放器过程发生错误,错误信息:%@",error);
            return nil;
        }
    }
    return _audioPlayer;
}

/**
 *  播放音频
 */
-(void)play{
    if (!self.audioPlayer.isPlaying) {
        [self.audioPlayer play];
        self.timer.fireDate = [NSDate distantPast];
    }
}

/**
 *  暂停播放
 */
-(void)pause{
    if (self.audioPlayer.isPlaying) {
        [self.audioPlayer pause];
        self.timer.fireDate = [NSDate distantFuture];
    }
}


//play
- (IBAction)clickplay:(id)sender {
    [self play];
}
//pause
- (IBAction)clickpause:(id)sender {
    [self pause];
}

#pragma mark - delegate
-(void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag{
    NSLog(@"播放完毕");
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        self.timer.fireDate = [NSDate distantFuture];
    });
}

-(void)audioPlayerDecodeErrorDidOccur:(AVAudioPlayer *)player error:(NSError *)error{
    NSLog(@"解码失败");
}
原文地址:https://www.cnblogs.com/iOSDeng/p/5089213.html