【问题标题】:iPhone: launching sound clip is not stopping when view changesiPhone:视图更改时启动声音剪辑不会停止
【发布时间】:2012-10-19 23:11:23
【问题描述】:

我有一个应用程序,它在启动时会播放一个介绍剪辑。以下代码位于 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 中并调用了委托,但我仍然没有任何运气。再次感谢您的帮助。

【问题讨论】:

    标签: xcode xcode4.3 avaudioplayer appdelegate


    【解决方案1】:

    我通过将 *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];}
    

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

    【讨论】:

    • 音频播放完毕后如何重复此操作? @meltrek
    • _startupPlayer.numberOfLoops = -1;//负数表示无限播放
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多