본문 바로가기
아이폰 개발/ios 개념&튜토리얼

iOS AVAudioPlayer 예제

by 인생여희 2021. 1. 26.

iOS AVAudioPlayer 예제

 

 

iOS AVAudioPlayer 개발순서

 

1. AVFoundation import

 

2.AVAudioPlayerDelegate 채택

 

3.프로퍼티 선언 및 시작, 정지 메소드 선언

 

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

@interface AudioPlayer : NSObject <AVAudioPlayerDelegate>

@property (nonatomic , strong) NSURL *fileURL;
@property (nonatomic, strong) AVAudioPlayer *audioPlayer;

-(void)play;
-(void)stop;


@end

 

 

4.오디오 세션 초기화 및 변수 초기화

 

#import "AudioPlayer.h"

@implementation AudioPlayer

@synthesize fileURL , audioPlayer;


- (id)init
{
    self = [super init];
    if (self) {
        
        
        //1.오디오 세션 초기화
        NSError *error = nil;
        
        if(![[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:&error]){
            NSLog(@"오디오 AVAudioSessionCategoryPlayback fail.... : %@" , error);
        }
        
        if (![[AVAudioSession sharedInstance] setActive:YES error:&error]) {
            NSLog(@"오디오 세션 활성화 fail... : %@" , error);
        }
        
        //2.URL 셋팅
        fileURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"audiofile" ofType:@"wav"]];
        NSLog(@"url : %@" , fileURL);
        
        
        //3.AudioPlayer 객체 생성
        audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:&error];
        
        //4.AudioPlayer 설정
        [audioPlayer setVolume:1.0];
        audioPlayer.numberOfLoops = 5;
        audioPlayer.delegate = self;
        
    }
    return self;
}

 

 

5.오디오 재생

 

//시작
-(void)play{
    

    // [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
       [audioPlayer prepareToPlay];
       [audioPlayer play];
    
}

 

 

6.오디오 멈춤

 

//종료
-(void)stop{
    [audioPlayer stop];
     audioPlayer = nil;
}

//Audioplayer 델리게이트 메소드
//오디오 재생이 종료되면 호출
-(void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag{
    NSLog(@"audioPlayerDidFinishPlaying 호출..finish..");
}

 

 

7. AppDelegate 에서 참조 및 호출해서 사용하기

 

#import <UIKit/UIKit.h>
#import "AudioPlayer.h"

@interface AppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow * window;

@property (nonatomic , strong) AudioPlayer *audio;
@end



#import "AppDelegate.h"
@interface AppDelegate ()

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    //오디오 플레이
    if (!self.audio) {
        self.audio = [[AudioPlayer alloc]init];
        [self.audio play];
    }
    return YES;
}
@end

 

 

예제 파일

 

avaudio.zip
0.00MB