使用UIAlertView无法播放声音
问题描述:
我的调整的一部分必须播放声音并在收到特定消息时显示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];
答
您的当前代码在显示警报后立即停止声音,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
答
集代表在.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");
}
是'网址()'各种各样的速记? – 2011-05-27 21:39:03
是的,我编辑了代码 – b1onic 2011-05-27 21:47:45
为了确认,'mySound'不是'nil'吧? – 2011-05-27 21:51:48