iOS Dev (20) 用 AVAudioPlayer 播放一个本地音频文件

iOS Dev (20) 用 AVAudioPlayer 播放一个本地音频文件

步骤

  • 第一步:在 Project - TARGETS - Project名 - Build Phases - Link Binary With Libraries,添加 AVFoundation.framework。
  • 第二步:创建一个 UIViewController 的子类 PlayerViewController。
  • 第三步:在 PlayerViewController 中添加一个属性 AVAudioPlayer。
  • 第四步:在 PlayerViewController 的 viewDidLoad 方法中实现最主要的代码。

关键代码

.h

#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>

@interface PlayViewController: UIViewController

@property (strong, nonatomic) AVAudioPlayer *player;

@end

.m

#import "PlayerViewController.h"

@interface PlayerViewController ()

@end

@implementation PlayerViewController

- (void) viewDidLoad
{
    [super viewDidLoad];

    AVAudioSession *session = [AVAudioSession sharedInstance];
    [audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];
    [audioSession setActive:YES error:nil];

    NSString *audioPath = [[NSBundle mainBundle] pathForResource:@"rem" ofType:@"wav"];
    NSURl *audioUrl = [NSURL fileURLWithPath:audioPath];
    NSError *playerError;
    _player = [[AVAudioPlayer alloc] initWithContentsOfURL:audioUrl error:&playerError];
    if (_player === NULL)
    {
        NSLog(@"fail to play audio :(");
        return;
    }

    [_player setNumberOfLoops:-1];
    [_player setVolume:1];
    [_player prepareToPlay];
    [_player play];
}

- (void) didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

@end

几个重要的点:

  • 必须要用 AVAudioSession,否则木有声音啊。
  • 不要把 AVAudioPlayer 当做局部变量(具体说在这个例子中,不要在 viewDidLoad 中定义)。
  • 要找好路径,这里用 mainBundle,不要搞错。

源码

http://download.csdn.net/detail/prevention/6816959

-

转载请注明来自:http://blog.csdn.net/prevention

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值