无法使用 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];
A part of my tweak must play a sound and display an UIAlertView when a certain message is received. Then when the UIAlertView is cancelled, the sound stops.
At the moment, the UIAlertView shows up, but the sound is not played. Here is my code
#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];
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您当前的代码在显示警报后立即停止声音,UIAlertViews 不会阻止 show 方法上的当前线程。
在这种情况下,您想要的是在警报解除后停止声音。为此,您必须为警报设置一个委托,该委托满足
UIAlertViewDelegate 协议
,然后,根据您想要停止声音的具体时间,您应该添加代码以在以下任一位置停止播放器:委托的以下方法:请注意,您必须保留对播放器的引用。
查看 UIAlertView 文档以了解有关其生命周期的更多信息。
Your current code is stopping the sound immediately after the alert is displayed, UIAlertViews do not block the current thread on the show method.
In this case what you want is to do stop your sound once the alert is dismissed. To do that you have to set a delegate for your alert, that fulfills the
UIAlertViewDelegate protocol
then, depending on exactly when you want to stop your sound, you should add the code to stop your player on one of the following methods of the delegate:Note that you are gonna have to keep a reference to your player.
Take a look at the UIAlertView documentation to learn more about its lifecycle.
在.h文件中设置委托:
以及上面声明的设置方法。
在 .m 文件中执行以下操作:
Set delegate in .h file:
And set method that above declared.
And in .m file do this: