在触摸事件中播放声音?

时间:2010-06-21 05:54:16

标签: iphone iphone-sdk-3.0

我正在使用以下代码在用户触摸屏幕的任何位置时播放声音但是无论何时我测试它都没有播放声音,当我在按钮上使用相同的代码时它会在第二次点击按钮时播放在第一次点击??

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 

{

UITouch *touch = [touches anyObject];


CGPoint point = [touch locationInView:self.view]; 
if (CGRectContainsPoint(CGRectMake(320,480,0,0),point));//CGRectMake(5, 5, 40, 130), point))
{
    AVAudioPlayer *player;
    if(!player){

        NSString* resourcePath = [[NSBundle mainBundle] resourcePath];
        resourcePath = [resourcePath stringByAppendingString:@"/try.wav"];
        NSLog(@"Path to play: %@", resourcePath);
        NSError* err;

        //Initialize our player pointing to the path to our resource
        player = [[AVAudioPlayer alloc] initWithContentsOfURL:
                  [NSURL fileURLWithPath:resourcePath] error:&err];

        if( err ){
            //bail!
            NSLog(@"Failed with reason: %@", [err localizedDescription]);
        }
        else{
            //set our delegate and begin playback
            player.delegate = self;
            [player play];
        }
    }

} 

}

1 个答案:

答案 0 :(得分:0)

AVAudioPlayer *player;   // <---
if(!player){

局部变量自动初始化为0.通常内容是一些非零垃圾,因此以下if条件很少会满足。

查看代码似乎会重用player。离开函数后,局部变量将丢失。因此,您应该使其成为视图的即时变量(ivar),或使其成为静态变量。

static AVAudioPlayer *player;   // <---
if(!player){