延迟背景音乐开始

时间:2013-12-10 16:27:47

标签: ios audio avfoundation appdelegate

我正在通过一个应用程序并添加我想要的功能,但随着时间的推移,我会遇到一些问题。

我希望有人能回答这个问题。

我想在我的应用上播放一些背景音乐,并且通过在AppDelegate中使用此代码实现了这一点

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{


    NSString* resourcePath = [[NSBundle mainBundle] resourcePath];
    resourcePath = [resourcePath stringByAppendingString:@"/smb1-1.mp3"];
    NSLog(@"Path to play: %@", resourcePath);
    NSError* err;

    //Initialize our player pointing to the path to our resource
    player = [[AVAudioPlayer alloc] initWithContentsOfURL:
              [NSURL fileURLWithPath:resourcePath] error:&err];

    if( err ){
        //bail!
        NSLog(@"Failed with reason: %@", [err localizedDescription]);
    }
    else{
        //set our delegate and begin playback
        player.delegate = self;
        [player play];
        player.numberOfLoops = -1;
        player.currentTime = 0;
        player.volume = 0.5;

    }

    // Override point for customization after application launch.
    return YES;
}

所以一切都很好。然而,我想要的是音频在应用程序完成启动后3秒开始播放,而不是直接播放。

有谁知道如何设置延迟或者可能以不同的方式解释。每次音乐修复之前,我都不会有延迟,只是第一次初次发布。

提前致谢。

1 个答案:

答案 0 :(得分:1)

希望这有帮助:

  1. 在你的appDelegate中创建一个BOOL iVar:

    @implementation aaaAppDelegate        
    {
        BOOL firstTime;
    }
    
  2. 将此添加到didFinishLaunchingWithOptions方法:

    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
    {
        // Override point for customization after application launch.
        firstTime = YES;
        return YES;
    }
    
  3. 将此添加到appDelegate中的applicationDidBecomeActive方法。

        - (void)applicationDidBecomeActive:(UIApplication *)application
        {
            if (firstTime)
            {
                firstTime = NO;
                [self performSelector:@selector(playMusic) withObject:nil afterDelay:3.0];
            }
        }
    
  4. 将您的音乐播放代码从didFinishLaunchingWithOptions移至名为playMusic的单独方法:

     -(void)playMusic
     {
         NSString* resourcePath = [[NSBundle mainBundle] resourcePath];
         resourcePath = [resourcePath stringByAppendingString:@"/smb1-1.mp3"];
         NSLog(@"Path to play: %@", resourcePath);
         NSError* err;
    
         //Initialize our player pointing to the path to our resource
         player = [[AVAudioPlayer alloc] initWithContentsOfURL:
         [NSURL fileURLWithPath:resourcePath] error:&err];
    
         if( err ){
             //bail!
             NSLog(@"Failed with reason: %@", [err localizedDescription]);
         }
         else{
             //set our delegate and begin playback
             player.delegate = self;
             [player play];
             player.numberOfLoops = -1;
             player.currentTime = 0;
             player.volume = 0.5;
    
         }
     }