2011-05-27 97 views
1

我的調整的一部分必須播放聲音並在收到特定消息時顯示UIAlertView。然後當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]; 
+0

是'網址()'各種各樣的速記? – 2011-05-27 21:39:03

+0

是的,我編輯了代碼 – b1onic 2011-05-27 21:47:45

+0

爲了確認,'mySound'不是'nil'吧? – 2011-05-27 21:51:48

回答

2

您的當前代碼在顯示警報後立即停止聲音,UIAlertViews不會阻塞show方法上的當前線程。

在這種情況下,您希望在警報解除後停止聲音。要做到這一點,你必須爲你的警報設置一個代表,然後完成UIAlertViewDelegate protocol,具體取決於你何時想停止你的聲音,你應該添加代碼來停止你的播放器在代理的以下方法之一:

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

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

請注意,你將不得不保留一個參考你的玩家。

查看UIAlertView文檔以瞭解更多關於其生命週期的信息。

+0

非常感謝,現在正在工作。 – b1onic 2011-05-28 15:02:29

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"); 
}