1

我的部分调整必须在收到特定消息时播放声音并显示 UIAlertView。然后当 UIAlertView 被取消时,声音停止。

目前, UIAlertView 出现了,但没有播放声音。这是我的代码

#define url(x) [NSURL URLWithString:x]

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Title" message:@"message" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil]; 

AVAudioPlayer *mySound;
mySound = [[AVAudioPlayer alloc] initWithContentsOfURL:url(@"/Library/Ringtones/Bell Tower.m4r") error:nil];


[mySound setNumberOfLoops:-1];  
[mySound play];

[alert show]; 
[alert release];
[mySound stop];
[mySound release];
4

2 回答 2

2

您当前的代码在显示警报后立即停止声音,UIAlertViews 不会阻塞 show 方法上的当前线程。

在这种情况下,您想要做的是在警报解除后停止声音。为此,您必须为您的警报设置一个委托,UIAlertViewDelegate protocol然后根据您想要停止声音的确切时间,您应该添加代码以在委托的以下方法之一上停止播放器:

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex

- (void)alertView:(UIAlertView *)alertView willDismissWithButtonIndex:(NSInteger)buttonIndex

请注意,您必须保留对播放器的引用。

查看 UIAlertView 文档以了解有关其生命周期的更多信息。

于 2011-05-27T21:54:42.030 回答
2

在 .h 文件中设置委托:

@interface ViewController : UIViewController <UIAlertViewDelegate>
{
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex;

@end

并设置上面声明的方法。

在 .m 文件中执行以下操作:

- (void)viewDidLoad
{
    [super viewDidLoad];
    NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/ma.mp3", [[NSBundle mainBundle] resourcePath]]];

    NSError *error;

    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Title" message:@"message" delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil]; 

    audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
    audioPlayer.numberOfLoops = -1;


    [audioPlayer play];

    [alert show]; 
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex==0) {
        [audioPlayer stop];

    }
    NSLog(@"U HAVE CLICKED BUTTON");
}
于 2012-10-24T06:38:09.907 回答