iPhone:视图更改时,启动声音片段不会停止

时间:2012-10-12 18:35:32

标签: xcode xcode4.3 avaudioplayer appdelegate

我有一个应用程序,当它启动它时播放一个介绍剪辑。以下代码位于appDelegate.m中的- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions内,该代码非常出色。

NSLog(@"PLAY SOUND CLIP WHILE LOADING APP");
NSURL *clip = [[NSBundle mainBundle] URLForResource: @"intro" withExtension:@"caf"];
self.startupPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:clip error:NULL];
[self.startupPlayer play];

如果用户在介绍声音结束前更改了视图,它仍会继续播放。我已将此代码置于- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions之外,认为它会有所帮助,但不会。

-(void)viewDidDisappear:(BOOL)animated {
[super viewDidDisappear:animated];
// Stop Sound
[self.startupPlayer stop];
}

我想也许如果我在加载请求之后立即放置一个if语句可能会有所作为,但它没有奏效。见例:

NSLog(@"PLAY SOUND CLIP WHILE LOADING APP");
NSURL *clip = [[NSBundle mainBundle] URLForResource: @"intro" withExtension:@"caf"];
self.startupPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:clip error:NULL];
[self.startupPlayer play];

if ([viewDidDisappear == YES]) {
[self.startupPlayer stop];
}

如果用户在播放完剪辑之前更改视图,那么任何可以停止介绍声音的建议都会很棒。哦,我已经成功地在应用程序的其他部分使用了“viewWillDisappear”,但在这种情况下,我选择“viewDidDisappear”,因为后者也没有用。所以我很难过。提前谢谢。

编辑:所以我将viewWillDisappear移动到我的MainViewController并调用了委托,但我仍然没有运气。再次,帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

我通过为@ startupPlayer获取@property声明并将其放在AppDelegate.h文件而不是它下面的方式来解决了这个问题;

在AppDelegate.m

@interface AppDelegate () 

@property (nonatomic, strong) AVAudioPlayer *startupPlayer;
@end

然后我仍然在.m文件中@synthesized它,如下所示,并保持didFinishLaunchingWithOptions相同:

@implementation AppDelegate 
@synthesize startupPlayer = _startupPlayer;

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

//------ PLAY SOUND CLIP WHILE LOADING APP -----

NSLog(@"PLAY SOUND CLIP WHILE LOADING APP");
NSURL *clip = [[NSBundle mainBundle] URLForResource: @"intro" withExtension:@"caf"];
self.startupPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:clip error:NULL];
[self.startupPlayer play]; }

然后在我的MainViewController.m

#import "AppDelegate.h"

-(void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
//stop intro sound
AppDelegate *introClip = (AppDelegate *)[[UIApplication sharedApplication]delegate];
[[introClip startupPlayer]stop];}

现在,即使介绍音乐仍在播放一个周期,用户也可以切换到另一个视图并停止播放音乐。