IOS Dev (20) uses AVAudioPlayer to play a local audio file
- Author: CSDN laruence
- Blog: http://blog.csdn.net/preventionstep
- Step 1: Add AVFoundation. framework in Project-TARGETS-Project name-Build Phases-Link Binary With Libraries.
- Step 2: Create a subclass of UIViewController PlayerViewController.
- Step 3: add an AVAudioPlayer attribute to PlayerViewController.
- Step 4: implement the most important code in the viewDidLoad method of PlayerViewController. Key code
. H
#import
#import @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
Important points: