2011-10-19 31 views
0

NSTimerを使用してAVAudioPlayerで音楽を再生しますが、[player prepareToPlay]が返されます。NO &はバックグラウンドで再生されません。AVAudioPlayerは、NSTimerをバックグラウンドで使用して音楽を再生できません。

誰か私にいくつかのアイデアを教えてもらえますか?

は、ここに私のコードです:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 
{ 
    [NSTimer scheduledTimerWithTimeInterval:10 target:self selector:@selector(playMusic:) userInfo:nil repeats:NO]; 
    [self.window makeKeyAndVisible]; 
    return YES; 
} 

- (void)playMusic:(NSTimer *)timer{ 
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil]; 
    NSString *fileName = [[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:@"Apologize.mp3"]; 
    NSURL *fileUrl = [NSURL fileURLWithPath:fileName]; 
    NSError *error; 
    AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:fileUrl error:&error]; 
    if ([player prepareToPlay]) { 
     [player play]; 
     NSLog(@"start!"); 
    }else{ 
     NSLog(@"error msg :%@",error); 
    } 
} 

- (void)applicationDidEnterBackground:(UIApplication *)application { 

    if ([[UIApplication sharedApplication] respondsToSelector:@selector(beginReceivingRemoteControlEvents)]){ 
     [[UIApplication sharedApplication] beginReceivingRemoteControlEvents]; 
    } 

    UIBackgroundTaskIdentifier backgroundTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{ 
    //  /* just fail if this happens. */ 
     [[UIApplication sharedApplication] endBackgroundTask:backgroundTask]; 
    }]; 
} 

答えて

0

コードに行く前に。あなたはバックグラウンドで音楽を演奏する許可が必要であることをOSに伝える必要があります。 アプリのInfo.plist

<key>UIBackgroundModes</key> 
    <array> 
      <string>audio</string> 
    </array> 

そうすることでキーを設定することによって、あなたが背景にアプリを移動するオーディオを再生できるようになることを行うことができます。

+0

私はplist.infoにキーを追加しましたが、それでもまだ再生できません... – Garen

+0

私はアプリで音楽を始めると、バックグラウンドで再生できます... 私は長い間狂っています。 。> _ < – Garen

0

サミフィッシャーの回答を続けると、apple's documentationを参照してください。問題が発生した場合は、previous postも参照してください。

+0

avaudioplayerはフォアグラウンドで起動するとバックグラウンドで再生できますが、NSTimerを使用してバックグラウンドで起動すると、[player prepareToPlay]メソッドは返されません。 – Garen

+0

avaudioplayerのデリゲートメソッドEndInterruptionを処理する必要があります。しかし、それは私のために働いていない...しかし、私はドキュメントを読んで、私はそれが働いていることがわかりました.... – DShah

0

私は同じ問題を持っていますが、私はこの記事から解決策が見つかりました:あなたはのviewDidLoadで、この初期化を実行する必要がありhttp://developer.apple.com/library/ios/#qa/qa1668/_index.html

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

AVAudioSession *audioSession = [AVAudioSession sharedInstance]; 

NSError *setCategoryError = nil; 
[audioSession setCategory:AVAudioSessionCategoryPlayback error:&setCategoryError]; 
if (setCategoryError) { /* handle the error condition */ } 

NSError *activationError = nil; 
[audioSession setActive:YES error:&activationError]; 
if (activationError) { /* handle the error condition */ } 
1

を:

NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:@"test" 
                  ofType:@"mp3"]; 
NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:soundFilePath]; 
self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL 
                  error:nil]; 
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents]; 

[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil]; 
[[AVAudioSession sharedInstance] setActive: YES error: nil]; 

これがためでありますオーディオの初期化。ここでは、という名前のMP3のテストがプロジェクトにインポートされています。 beginReceivingRemoteControlEvents部分は非常に重要です。それがなければ、バックグラウンドから演奏を始めることはできません。すでにフォアグラウンドから演奏している音楽を聴いてください。

今、あなたはが(アプリデリゲートのapplicationDidEnterBackgroundで行くことができますが、あなたはそれが属するクラスのコードを置くことができるこの方法)をdidEnterInBackGroundイベントに耳を傾ける必要があります。

[[NSNotificationCenter defaultCenter] addObserver:self 
             selector:@selector(didEnterBG:) 
              name:UIApplicationDidEnterBackgroundNotification 
              object:nil]; 

そして今、そのdidEnterBG方法で:ここ

self.backgroundTimer = [NSTimer scheduledTimerWithTimeInterval:10.0 target:self selector:@selector(backgroundWork) userInfo:nil repeats:YES]; 
[self.backgroundTimer fire]; 

私はすべてこの音の繰り返しを行います10sは個人的な理由からですが、必要なものは何でもしてください。最後に 、backgroundWork方法:

- (void)backgroundWork{ 
    [self.audioPlayer prepareToPlay]; 
    [self.audioPlayer play]; 
} 

今、あなたのオーディオファイルが

:-)バックグラウンドで再生されているまた、あなたのアプリがバックグラウンドで仕事をして維持するために特定の権利を持っている必要があることに注意してください。 'YourTarget' - > Capabilities - > Background Modes:Audio and AirPlayのチェックボックスをオンにする必要があります。それ以外の場合、OSは実際の状態(デバッガや計測器なし)で数分間であなたのアプリケーションを終了させます。

+0

これは本当に有用ですが、私はバックグラウンドモードでのみサウンドを開始する場合は? [self.backgroundTimer fire]を使用するとbackgroundWorkが呼び出され、アプリはそのサウンドを再生するので – Signo

+0

バックグラウンドの仕事関数が 'UIApplicationDidEnterBackgroundNotification'で呼び出されるので、アプリは実際にバックグラウンドモードで入力されたときにのみ再生されます。 –

関連する問題