gpt4 book ai didi

objective-c - IOS 我可以在 appDelegate 上使用 AVAudioPlayer 吗?

转载 作者:可可西里 更新时间:2023-11-01 17:02:05 25 4
gpt4 key购买 nike

我有一个带有两个选项卡的 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];
}

但我在 UIApplicationMain 上收到错误 Program received signal: "SIGABRT"

有没有更好的方法来完成我想做的事情?如果我应该这样做,我应该从哪里开始检查问题?

最佳答案

是的,您可以在 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

现在实现委托(delegate)方法

#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;


}
}
}

关于objective-c - IOS 我可以在 appDelegate 上使用 AVAudioPlayer 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8410407/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com