12

AVAudioPlayerかなりシンプルだと思ったMP3を再生しようとしています。残念ながら、それは完全には機能していません。これが私がしたすべてです:

  • テストのために、Xcodeで新しいiOSアプリケーション(シングルビュー)を作成しました。
  • AVFoundationフレームワークをプロジェクトとに追加しまし#import <AVFoundation/AVFoundation.h>ViewController.m

  • アプリの「ドキュメント」フォルダにMP3ファイルを追加しました。

  • ViewControllers viewDidLoad:を次のように変更しました。

コード:

- (void)viewDidLoad
{
    [super viewDidLoad];        

    NSString* recorderFilePath = [NSString stringWithFormat:@"%@/MySound.mp3", [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"]];    

    AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:recorderFilePath] error:nil];
    audioPlayer.numberOfLoops = 1;

    [audioPlayer play];

    //[NSThread sleepForTimeInterval:20];
}

残念ながら、オーディオは再生を開始した直後に明らかに停止します。コメントを外すsleepForTimeIntervalと、20秒間再生され、その後停止します。この問題は、ARCでコンパイルする場合にのみ発生します。それ以外の場合は、問題なく動作します。

4

3 に答える 3

7

問題は、ARCallocでコンパイルするとき、コンパイラが呼び出しを挿入することによって「不均衡」を自動的に修正するため、存続させたいインスタンスへの参照を保持する必要があることですrelease(少なくとも概念的には、詳細についてはMikesAshのブログ投稿を参照してください) )。これは、インスタンスをプロパティまたはインスタンス変数に割り当てることで解決できます。

Phlibboの場合、コードは次のように変換されます。

- (void)viewDidLoad
{
    [super viewDidLoad];        
    NSString* recorderFilePath = [NSString stringWithFormat:@"%@/MySound.mp3", [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"]];    
    AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:recorderFilePath] error:nil];
    audioPlayer.numberOfLoops = 1;
    [audioPlayer play];
    [audioPlayer release]; // inserted by ARC
}

また、AVAudioPlayer参照が残っていない場合は割り当てが解除されるため、すぐに再生が停止します。

私自身はARCを使用したことがなく、簡単に読んだだけです。これについてもっと知っているなら、私の答えにコメントしてください。私はそれをより多くの情報で更新します。

ARCの詳細情報:
ARCリリースノートへの移行
LLVM自動参照カウント

于 2011-10-12T18:37:09.923 に答える
3

AVAudioPlayerをヘッダーファイルのivarとして使用しますstrong

@property (strong,nonatomic) AVAudioPlayer *audioPlayer
于 2012-03-30T22:46:34.657 に答える
3

複数のAVAudioPlayerを同時に再生する必要がある場合は、NSMutableDictionaryを作成します。キーをファイル名として設定します。次のように、デリゲートコールバックを介して辞書から削除します。

-(void)playSound:(NSString*)soundNum {


    NSString* path = [[NSBundle mainBundle]
                      pathForResource:soundNum ofType:@"m4a"];
    NSURL* url = [NSURL fileURLWithPath:path];

    NSError *error = nil;
    AVAudioPlayer *audioPlayer =[[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];

    audioPlayer.delegate = self;

    if (_dictPlayers == nil)
        _dictPlayers = [NSMutableDictionary dictionary];
    [_dictPlayers setObject:audioPlayer forKey:[[audioPlayer.url path] lastPathComponent]];
    [audioPlayer play];

}

-(void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag {        
   [_dictPlayers removeObjectForKey:[[player.url path] lastPathComponent]];
}
于 2013-07-10T09:04:48.493 に答える