1. 程式人生 > >IOS 音訊播放器

IOS 音訊播放器

例項:1.新建Empty Application專案,新增HomeViewController頁面

 HomeViewController.h程式碼如下:

#import <UIKit/UIKit.h> #import <AVFoundation/AVFoundation.h> @interface HomeViewController : UIViewController <AVAudioPlayerDelegate>{ }

@end 

 HomeViewController.m程式碼如下:

#import "HomeViewController.h" @interface HomeViewController () @end @implementation HomeViewController - (void)playAudioFile:(NSString *)soundFileName{
    NSString *fileName = [[NSBundle mainBundle] pathForResource:soundFileName                                                           ofType:@"mp3"];     NSURL *fileUrl = [NSURL fileURLWithPath:fileName];     NSError *error = nil;     AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:fileUrl error:&error];
    if (!player) {     } else {         [player setNumberOfLoops:-1]; //預設為0,即播放一次就結束;如果設定為負值,則音訊內容會不停的迴圈播放下去。         [player setDelegate:self];         [player play];     } }

//程式中斷時,暫停播放 

- (void)audioPlayerBeginInterruption:(AVAudioPlayer *)player{     [player pause]; }

//程式中斷結束返回程式時,繼續播放 

- (void)audioPlayerEndInterruption:(AVAudioPlayer *)player{
    [player play]; } - (void)viewDidLoad {     [self playAudioFile:@"mm"];//播放音訊     [super viewDidLoad]; }

@end