iOS 音声再生(AVAudioPlayer)

プロフェッショナルプログラマーと同じ内容です。

iOS, Mac OS でのオーディオ再生のためのObjective-Cインタフェースを提供するAVAudioPlayerの使い方
(Mac OS Xでも同じです)

AVAudioPlayer は, ハイレベルAPIです。細かい制御が必要な場合は, AudioQueueなんかの低レベルAPIを使う必要があります。

AVAudioPlayerでできること

  • 任意の所要時間のサウンドの再生
  • ファイルまたはメモリバッファからのサウンドの再生
  • サウンドのループ再生
  • 複数のサウンドの同時再生
  • 再生中の各サウンドの相対的な再生レベルの制御
  • サウンドファイル内での特定の位置へのシーク(早送りや巻き戻しなどのアプリケーション機能
    をサポートします
  • オーディオレベル測定機能に使用できるデータの取得

サポートするフォーマット

AIFF .aif, .aiff
CAF .car
MPEG-1, Layer3 .mp3
MPEG-2 .aac
MPEG4 .m4a, mp4
WAV .wav

サンプル

手順

  1. AVFoundation.framework を Link Binary With Libraries に追加する
  2. UI などを用意する
  3. コード

時間

※ちなみに音声の時間を取得するには duration プロパティを利用します

NSTimeInterval ti = self.player.duration; // self.player は, AVAudioPlayerのインスタンス

時間に変換するには

int minutes = floor(ti / 60);
int second = round(ti - minutes * 60);
NSLog(@"%02d:%02d", minutes, second); // これで 03:00 みたいな表記もできる

コード

このプログラムは, View のスタート時に, AVAudioPlayer を初期化して,
再生終了時には, ログを出します。(AVAudioPlayerDelegate を実装)

AVAudioPlayerDelegate は, audioPlayerDidFinishPlaying を提供します。これを使って, 終了時の動作を定義します。

ちなみに, ここで, AVAudioPlayerをもう1つ用意して, delegate を同じクラスに指定して, audioPlayerDidFinishPlaying でもう1つをスタートさせれば, 2つの音声を連続再生できたりします

ViewController.h

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

@interface ViewController : UIViewController

@property(nonatomic) AVAudioPlayer *player;
@property (weak, nonatomic) IBOutlet UIButton *playButton;

- (IBAction)playClick:(id)sender;
@end

ViewController.m

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

@synthesize player;

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

-(void)prepareAudio
{
    NSError *error = nil;
    NSString *path = [[NSBundle mainBundle] pathForResource:@"ng" ofType:@"wav"];
    NSURL *url = [[NSURL alloc] initFileURLWithPath:path];
    player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
    
    if ( error != nil )
    {
        NSLog(@"Error %@", [error localizedDescription]);
    }
    [self.player prepareToPlay];
    [self.player setDelegate:self];
    NSTimeInterval ti = self.player.duration;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)playClick:(id)sender
{
    if ( self.player.playing )
    {
        [self.player pause];
        [self.playButton setTitle:@"Pause" forState:UIControlStateNormal];
    }
    else
    {
        [self.player play];
        [self.playButton setTitle:@"Play" forState:UIControlStateSelected];
    }
}

#pragma mark - AVAudioPlayerDelegate
-(void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
    if ( flag )
    {
        NSLog(@"Done");
        [self.playButton setTitle:@"Start" forState:UIControlStateNormal];
        
        // Can start next audio?
    }
}
@end

NSDataを再生

initWithData(– (id)initWithData:(NSData *)data error:(NSError **)outError)を利用して,
NSData *を取得して再生することもできます。Formatは上に同じです。

Ref

Apple Developer