IOS can I use AVAudioPlayer on the appDelegate?

早过忘川 提交于 2019-12-06 01:44:01

yes you can use AVAudioPlayer in App Delegate.

What you need to do is:- In appDelegate.h file do:-

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

AVAudioPlayer *_backgroundMusicPlayer;
BOOL _backgroundMusicPlaying;
BOOL _backgroundMusicInterrupted;
UInt32 _otherMusicIsPlaying;

Make backgroundMusicPlayer property and sythesize it.

In appDelegate.m file do:-

Add these lines in did FinishLaunching method

NSError *setCategoryError = nil;
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryAmbient error:&setCategoryError];

    // Create audio player with background music
    NSString *backgroundMusicPath = [[NSBundle mainBundle] pathForResource:@"SplashScreen" ofType:@"wav"];
    NSURL *backgroundMusicURL = [NSURL fileURLWithPath:backgroundMusicPath];
    NSError *error;
    _backgroundMusicPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:backgroundMusicURL error:&error];
    [_backgroundMusicPlayer setDelegate:self];  // We need this so we can restart after interruptions
    [_backgroundMusicPlayer setNumberOfLoops:-1];   // Negative number means loop forever

Now implement delegate methods

#pragma mark -
#pragma mark AVAudioPlayer delegate methods

- (void) audioPlayerBeginInterruption: (AVAudioPlayer *) player {
    _backgroundMusicInterrupted = YES;
    _backgroundMusicPlaying = NO;
}

- (void) audioPlayerEndInterruption: (AVAudioPlayer *) player {
    if (_backgroundMusicInterrupted) {
        [self tryPlayMusic];
        _backgroundMusicInterrupted = NO;
    }
}

- (void)tryPlayMusic {

    // Check to see if iPod music is already playing
    UInt32 propertySize = sizeof(_otherMusicIsPlaying);
    AudioSessionGetProperty(kAudioSessionProperty_OtherAudioIsPlaying, &propertySize, &_otherMusicIsPlaying);

    // Play the music if no other music is playing and we aren't playing already
    if (_otherMusicIsPlaying != 1 && !_backgroundMusicPlaying) {
        [_backgroundMusicPlayer prepareToPlay];
        if (soundsEnabled==YES) {
            [_backgroundMusicPlayer play];
            _backgroundMusicPlaying = YES;


        }
    }   
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!