AVAudioPlayerを使った音楽ファイルの再生

AVAudioPlayerを使って音楽を再生する方法です。再生時間をNSTimerを使って表示しています。NSRunLoopでも表示は可能かと思いますがNSTimerのほうがはるかに楽です。

githubにもございます。
GitHub - kmusiclife/AudioPlayer: This is AudioPlayer class extends AVAudioPlayer written by Objective-C

.hファイル

#include <AVFoundation/AVFoundation.h>
@interface audioplayer : NSObject 
<AVAudioPlayerDelegate>
{
    NSTimer * timer;
    AVAudioPlayer * audio;
}
@end

.mファイル

// 音楽再生を開始
@implementation audioplayer
- (void)main 
{
    [super viewDidLoad];
    NSString * path = [[NSBundle mainBundle] pathForResource:@"soundfile" ofType:@"mp3"];
    NSURL * url = [NSURL fileURLWithPath:path];
    // errorを取得したいときはscheduledTimerWithTimeIntervalのerrorにNSError errorポインタ(&error)を投げます
    audio = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
    audio.delegate = self;
    [audio play];
    timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(playSequence) userInfo:nil repeats:YES];
    
}
// 再生時間を表示
- (void) playSequence{
    if(audio.playing){
        NSLog(@"%@", [NSString stringWithFormat:@"%f", audio.currentTime]);
    } else {
        [timer invalidate];
    }    
}
@end

ちなみにNSRunLoopを使うと下記のような記述になります。NSTimerのほうがいいですね。

    NSDate *now = [[NSDate alloc]init];
    NSTimer *timer = [[NSTimer alloc]initWithFireDate:now interval:0.1 target:self selector:@selector(playing) userInfo:nil repeats:YES];
    NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
    [runLoop addTimer:timer forMode:NSDefaultRunLoopMode];
    [runLoop run];