我有一个带有两个标签的TabBarController,我想在两个标签上播放音乐。现在我在主appDelegate上有我的代码

NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle]
                                         pathForResource:@"My Song"
                                         ofType:@"m4a"]]; // My Song.m4a

NSError *error;
    self.audioPlayer = [[AVAudioPlayer alloc]
            initWithContentsOfURL:url
            error:&error];
if (error)
{
    NSLog(@"Error in audioPlayer: %@",
        [error localizedDescription]);
} else {
    //audioPlayer.delegate = self;
    [audioPlayer prepareToPlay];
}

但我在Program received signal: "SIGABRT"上收到错误UIApplicationMain
有没有更好的方法来完成我要做的事情?如果这是我应该怎么做,应该从哪里开始检查问题?

最佳答案

是的,您可以在App Delegate中使用AVAudioPlayer。

您需要做的是:
在appDelegate.h文件中执行:

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

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

设置backgroundMusicPlayer属性并对其进行合成。

appDelegate.m文件中执行:-

在did FinishLaunching方法中添加这些行
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

现在实现委托方法
#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;


        }
    }
}

10-08 01:35