2012-01-01 90 views
1

我一直在殴打我的头对所有试图找出我的程序中的一个奇怪的声音问题。我将发布下面的代码。作为一个简短的描述,我有一个函数传递一个变量,并且决定应该播放哪种类型的声音,在该函数中,我有多个达到类别的声音,所以我使用arc4random语句,然后通过switch语句。发生的事情是,它会从case语句中发出两个声音,而不是一个,大多数情况下,如果我使用按钮进行两次调用,第二次它会从第一次播放声音并发出新声音,在相同的顶部播放相同的内容,但稍有延迟。我在开关中放置了一个断点,当它重复播放时,它只会经过开关一次,这真的很让人困惑。有一点需要注意的是,在此之前,我确实播放了另一种声音,但它使用了一个单独的AVAudioplayer和路径变量,因此它不应该成为问题,因为它从来不会像我正在播放的其他声音播放第二个声音。当我按下按钮时,我只调用一次函数,所以我不确定它为什么会这样做。我已经尝试将*路径和* avaudioplayer变量放入函数中,但它根本不会播放。在这里搜索,似乎在它有机会播放它之前,arc会释放它。我最终试图将它作为全局变量放在我的.m文件的顶部,然后设置实际路径并在开关内播放声音。声音会播放,但会播放两次..希望有人能帮助我。我尝试将avaudioplayer定义作为一个属性,它也做同样的事情。这是我的代码片段。而在此先感谢...iOS AVAudioPlayer双声音播放问题与Xcode 4.2和ARC

在.m文件

// Just below my synthesize statements 
NSString *path; 
AVAudioPlayer *theSound 

// My code that I call when the button is pressed 
[self playVoice:@"buyVoice"]; 

// The playVoice function 
- (void)playVoice:(NSString*)voiceNum; 

    if ([voiceNum isEqualToString:@"buyVoice"]) // Bought an Item Time for a voice 
    { 
     // play coin sound 
     [self coinSound]; 

     // play random buy phrase and coin sound 
     int phraseNumber = 0; 
     phraseNumber = arc4random() %(3); 

     switch (phraseNumber) 
     { 
      case 0: 
      { 
       path = [[NSBundle mainBundle] pathForResource:@"sndBuy1" ofType:@"m4a"]; 
        theSound =[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath: path] error:NULL]; 
        [theSound setNumberOfLoops:0]; 
        [theSound play]; 
        break; 
      } 

      case 1: 
      { 
       path = [[NSBundle mainBundle] pathForResource:@"sndBuy2" ofType:@"m4a"]; 
        theSound =[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath: path] error:NULL]; 
        [theSound setNumberOfLoops:0]; 
        [theSound play]; 
        break; 
      } 

      case 2: 
      { 
       path = [[NSBundle mainBundle] pathForResource:@"sndBuy3" ofType:@"m4a"]; 
        theSound =[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath: path] error:NULL]; 
        [theSound setNumberOfLoops:0]; 
        [theSound play]; 
        break; 
      } 

      case 3: 
      { 
       path = [[NSBundle mainBundle] pathForResource:@"sndBuy4" ofType:@"m4a"]; 
        theSound =[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath: path] error:NULL]; 
        [theSound setNumberOfLoops:0]; 
        [theSound play]; 
        break; 
      } 
    } 
} 
+0

嗨汤米...我修改了你的代码格式,但是我希望在你的' - (void)playVoice:(NSString *)voiceNum;'是原始复制和粘贴中的错误。它应该是' - (void)playVoice:(NSString *)voiceNum {'(即** {**而不是**; **)。 – 2012-01-01 17:10:35

+0

谢谢迈克尔,这不是一个错字,但从那以后我就修正了它。在更多的代码中,我发现问题出在哪里。在我的硬币声音功能中,我使用与声音相同的路径。我不相信我昨天没有看到。我想这就是你在熬夜半夜编码时得到的结果。 – TommyT39 2012-01-01 17:32:55

回答

7

组验证码ü玩之前Audio音效

这将重置玩家开始:

[theSound setCurrentTime:0.0]; 
[theSound play]; 

试试这个