iphone开发之音频播放类AVAudioPlayer的使用——加纯代码案例

1、本节目标
(1)使用AVAudioPlayer类播放音频
(2)掌握后台播放音乐
(3)自定义后台任务
(5)使用MPMoviePlayer
2、IOS音频播放概述
(1)IOS系统中的音频播放方式
AVAudioPlayer、AVPlayer、系统声音、音频队列
(2)AVAudioPlayer:
使用简单方便,但是只能播放本地音频,不支持流媒体播放
(3)AVPlayer
IOS4.0以后,可以使用AVPlayer播放本地音频和支持流媒体播放,但提供接口较少,处理音频不够灵活。
(4)音频队列
音频队列主要处理流媒体播放,提供了强大且灵活的API接口(C函数的接口),但是处理起来也较为复杂。
3、AVAudioPlayer的使用
(1)引用框架:使用AVAudioPlayer或AVPlayer需要引用AVFoundation类库。
处理音频示例:
NSBundle *bundle = [NSBundle mainBundle];
// 音频文件路径
NSString *urlString = [bundle pathForResource: @“第一夫人”ofType: @“mp3”];
// 初始化本地的URL
NSURL *url = [NSURL URLWithString:urlString];
//初始化音频对象
AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
//分配播放所需要的资源,并将其加入内部播放队列
[player prepareToPlay];
//播放
if([player plauy])
{
NSLog(“正在播放”);
}
(2)AVAudioPlayer常用属性
1> 音量
player.volume = 0.8 ; // 0.0~1.0之间
2>循环次数
player.numberOfLoops = 3; // 如果默认的话只播放一次
player.duration // 总时长
3>播放的时间位置
player.currentTime = 15.0; //指定从任意位置开始播放
4>声道数
NSUInteger channels = player.numberOfChannels; // 只读属性
5>常用方法
[player play]; // 播放
[player stop]; // 停止
[player pause]; // 暂停
4、AVAudioPlayer代理方法
-(void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL) flag
{
// 播放完成时需要执行的动作
}


-(void)audioPlayerDecodeErrorDidOccur:(AVAudioPlayer *)player error:(NSError *)error{
// 解码错误时执行的动作
}


-(void)audioPlayerBeginInterruption:(AVAudioPlayer *)player{
// 处理中断的代码,比如来电话时视频播放被暂停
}

-(void)audioPlayerEndInterruption:(AVAudioPlayer *)player{
// 处理中断结束的代码,打过电话后继续播放等等

}

代码验证,示例如下:

导入AVFoundation框架



导入要播放的音频文件

编辑控制器的.h文件如下:

//
//  ViewController.h
//  音频播放器
//
//  Created by apple on 15/9/5.
//  Copyright (c) 2015年 LiuXun. All rights reserved.
//

#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
@interface ViewController : UIViewController  <AVAudioPlayerDelegate>
{
    BOOL interrFlag;  // 中断前的播放状态,如果正在播放赋值为YES
}

@property (nonatomic, strong)  NSTimer *timer; // 不断循环执行某件事
@property (nonatomic, strong) UISlider *volumeSlider;  // 用于调节声音
@property (nonatomic, strong) UISlider *currentSlider;  // 用于调节进度
@property (nonatomic, strong ) UILabel *timeLabel;     // 用于显示播放时间
@property (nonatomic, strong) UIButton *btnPauseAndPlay;  // 播放与暂停按钮
@property (nonatomic, strong) AVAudioPlayer *avPlayer;  // 把播放音频的类对象声明为全局变量

-(void) sliderAction:(UISlider *) sender;  // 监听所有滑动条的事件
-(void)btnAction; // 监听按钮的事件
@end

编辑控制器的.m文件如下:

//
//  ViewController.m
//  音频播放器
//
//  Created by apple on 15/9/5.
//  Copyright (c) 2015年 LiuXun. All rights reserved.
//

#import "ViewController.h"
#define WIDTH    [UIScreen mainScreen].bounds.size.width
#define  HEIGHT   [UIScreen mainScreen].bounds.size.height
@interface ViewController ()

@end

@implementation ViewController

-(void) playAV   // 把播放音频的功能封装在此方法中
{
	NSError *error;
    
    // 设置音频会话支持后台播放
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:&error];
    
    // 获取指定音频文件的地址
    NSString *path = [[NSBundle mainBundle] pathForResource:@"第一夫人" ofType:@"mp3"];
    
    // 创建NSURL对象
    NSURL *url = [NSURL fileURLWithPath:path]; // 因为方法名已经有file指明了协议头为本地文件
    
    
    // 为音频播放类的对象开辟空间
    self.avPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
    _avPlayer.delegate = self;
    if (! self.avPlayer.playing) {
        [self.avPlayer play];
    }
}

-(void) zjLayout   // 此方法封装各种组件
{
    // 音量
    UILabel * lblVolume =  [[UILabel alloc] initWithFrame:CGRectMake(20, 30, WIDTH, WIDTH/6)];
    lblVolume .text = @"音量";
    lblVolume.textAlignment = NSTextAlignmentLeft;
    self.volumeSlider = [[UISlider alloc] initWithFrame:CGRectMake(WIDTH/5, 30, WIDTH*0.6, WIDTH/6)];
    [self.view addSubview:self.volumeSlider];
    [self.view addSubview:lblVolume];
    self.volumeSlider.minimumValue = 0.0;   // 因为音量的最值是0.0
    self.volumeSlider.maximumValue = 1.0;  // 音量的最大值是1
    self.volumeSlider.tag = 1;
    [self.volumeSlider addTarget:self action:@selector(sliderAction:) forControlEvents:UIControlEventTouchUpInside];
    
    //进度
    UILabel * lblCurrent =  [[UILabel alloc] initWithFrame:CGRectMake(20, 30+WIDTH/6, WIDTH, WIDTH/6)];
    lblCurrent .text = @"进度";
    lblCurrent.textAlignment = NSTextAlignmentLeft;
    self.currentSlider = [[UISlider alloc] initWithFrame:CGRectMake(WIDTH/5, 30+WIDTH/6, WIDTH*0.6, WIDTH/6)];
    [self.view addSubview:lblCurrent];
      [self.view addSubview:self.currentSlider];
    self.currentSlider.minimumValue = 0.0;
    self.currentSlider.maximumValue = self.avPlayer.duration; // 播放的总时长

    self.currentSlider.tag = 2;
    [self.currentSlider addTarget:self action:@selector(sliderAction:) forControlEvents:UIControlEventTouchUpInside];
    
    // 播放暂停按钮
    self.btnPauseAndPlay = [[UIButton alloc] initWithFrame:CGRectMake(20, 40+WIDTH/3, WIDTH/6, WIDTH/8)];
    [self.btnPauseAndPlay setTitle:@"暂停" forState:UIControlStateNormal];
    [self.btnPauseAndPlay addTarget:self action:@selector(btnAction) forControlEvents:UIControlEventTouchUpInside];
    [self.btnPauseAndPlay setBackgroundColor:[UIColor darkGrayColor]];
    [self.view addSubview:self.btnPauseAndPlay];
    
    // 播放时间显示标签
    self.timeLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 40+WIDTH/3+WIDTH/8, WIDTH, WIDTH/8)];
    self.timeLabel .text = [NSString stringWithFormat:@"剩余时长: %.0f  已播放: %.0f",self.avPlayer.duration,0.0];
   
    [self.view addSubview:self.timeLabel];
    
    // 利用NStimer计时器来刷新时间标签,和滚动条的滚动值
    self.timer =[NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
   
    [self playAV]; // 必须先调用播放音频的功能,然后才能给总时长duration赋值供组件使用
     [self  zjLayout];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)timerAction
{      // 剩余时间
    double syTime = self.avPlayer.duration - self.avPlayer.currentTime;
    self.timeLabel.text = [NSString stringWithFormat:@"剩余时长: %.0f  已播放: %.0f",syTime,self.avPlayer.currentTime];
    
      // 让滑动条跟随播放进度滚动
    self.currentSlider.value = self.avPlayer.currentTime;

}

-(void) sliderAction:(UISlider *)sender  // 监听所有滑动条的滑动事件
{
    switch (sender.tag) {
        case 1:
            self.avPlayer.volume = sender.value;
            break;
            
        case 2:
            self.avPlayer.currentTime = sender.value;
            break;
    }
}

-(void)btnAction   // 此方法监听按钮的点击事件
{
    if (self.avPlayer.isPlaying) {
        [self.avPlayer pause];
        [self.btnPauseAndPlay setTitle:@"播放" forState:UIControlStateNormal];
        // 开始播放时重新启动计时器功能
        self.timer =[NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
    }
    else
    {
        [self.avPlayer play];
        [self.btnPauseAndPlay setTitle:@"暂停" forState:UIControlStateNormal];
        [self.timer invalidate]; // 播放暂停时让计时器报废
    }
}

 // 以下处理AVAudioPlayerDelegate代理协议中方法

-(void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
    NSLog(@"音频播放完成");
}
-(void)audioPlayerDecodeErrorDidOccur:(AVAudioPlayer *)player error:(NSError *)error
{
    NSLog(@"解码错误");
}

-(void) audioPlayerBeginInterruption:(AVAudioPlayer *)player
{  // 当打电话时就打断了音频的播放,需要把它暂停
    
    if (player.isPlaying) {  // 当正在播放时,暂停即可
        [self  btnAction];
        interrFlag = YES;
    }
}

-(void) audioPlayerEndInterruption:(AVAudioPlayer *)player withOptions:(NSUInteger)flags
{ // 当中断结束时,重返原来状态
    if (interrFlag ) {
        [self btnAction];
        interrFlag = NO;
    }
}
@end
运行结果如下:






  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值