2015年8月28日 星期五

iOS筆記:AVFoundation.framework

建立播放音樂的app, 先匯入AVFoundation.h 標頭檔以及AVAudioPlayerDelegate協定. 再宣告一個AVAudioPlayer型態的變數audioPlayer來播放音樂.

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

@interface ViewController : UIViewController <AVAudioPlayerDelegate>
{
    AVAudioPlayer *audioPlayer;
    NSTimer *timer;
}

@property (strong, nonatomic) IBOutlet UISlider *slider;

- (void)ticker:(NSTimer *)theTimer;

@end

初始化 audioPlayer變數, 並設定代理人類別為ViewController, 目的為當音樂播放過程中被某些因素中斷時, 程式可以回應這個中斷, 並且當中斷因素結束後, 可以恢復音樂播放.

先找到music.mp3的路徑, 再進行初始化等動作.

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"music" ofType:@"mp3"];
    NSData *fileData = [NSData dataWithContentsOfFile:filePath];

    audioPlayer = [[AVAudioPlayer alloc] initWithData:fileData error:nil];

    audioPlayer.delegate = self;

    if (audioPlayer != nil) {
        if ([audioPlayer prepareToPlay]) {
            self.slider.minimumValue = 0;
            self.slider.maximumValue = audioPlayer.duration;
            self.slider.value = 0;
            [audioPlayer play];

           #啟動計時器
            timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(ticker:) userInfo:nil repeats:YES];
        }
    } 
}

當音樂被中斷時呼叫下列方法.

- (void)audioPlayerBeginInterruption:(AVAudioPlayer *)player
{
    NSLog(@"音樂中斷");
}

從flags參數判斷音樂中斷時的狀況.

- (void) audioPlayerEndInterruption:(AVAudioPlayer *)player withOptions:(NSUInteger)flags
{
    NSLog(@"音樂中斷結束");
    if (flags == AVAudioSessionInterruptionOptionShouldResume) {
        [player play];
    }
}

ticker方法為當計數器被觸發後呼叫的. 根據計時器的設定, 這個方法每一秒都會被呼叫一次, 因為在這個方法中我們更新slider的值, 讓他跟音樂的進度一致.

changePlayTime為當我們去調整slider目前的值時會跟著改變音樂的播放進度.

- (void)ticker:(NSTimer *)theTimer
{
    self.slider.value = audioPlayer.currentTime;
}

- (IBAction)changePlayTime:(id)sender
{
    audioPlayer.currentTime = self.slider.value;
}

enter image description here

參考:
http://www.appcoda.com/ios-avfoundation-framework-tutorial/

沒有留言:

張貼留言