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

.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 に答える
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 に答える