Can't play a sound with an UIAlertView
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;
myS开发者_如何学Cound = [[AVAudioPlayer alloc] initWithContentsOfURL:url(@"/Library/Ringtones/Bell Tower.m4r") error:nil];
[mySound setNumberOfLoops:-1];
[mySound play];
[alert show];
[alert release];
[mySound stop];
[mySound release];
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:
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
- (void)alertView:(UIAlertView *)alertView willDismissWithButtonIndex:(NSInteger)buttonIndex
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.
Set delegate in .h file:
@interface ViewController : UIViewController <UIAlertViewDelegate>
{
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex;
@end
And set method that above declared.
And in .m file do this:
- (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");
}
精彩评论