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 方法中實現最主要的代碼。

關鍵代碼

.hsession

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

@interface PlayViewController: UIViewController

@property (strong, nonatomic) AVAudioPlayer *player;

@end

.moop

#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/6816959ui

-atom

轉載請註明來自:http://blog.csdn.net/prevention.net

相關文章
相關標籤/搜索