AVAudioPlayer Help: Playing multiple sounds simultaneously, stopping them all at once, and working around Automatic Reference Counting

后端 未结 1 1921
情深已故
情深已故 2020-12-09 07:25

I am trying to create buttons that play single sound files and one button that stops all of the sounds that are currently playing. If

相关标签:
1条回答
  • 2020-12-09 08:00

    First off, put the declaration and alloc/init of audioplayer on the same line. Also, you can only play one sound per AVAudioPlayer BUT you can make as many as you want simultaneously. And then to stop all of the sounds, maybe use a NSMutableArray, add all of the players to it, and then iterate though and [audioplayer stop];

    //Add this to the top of your file
    NSMutableArray *soundsArray;
    
    //Add this to viewDidLoad
    soundsArray = [NSMutableArray new]
    
    //Add this to your stop method
    for (AVAudioPlayer *a in soundsArray) [a stop];
    
    //Modified playSound method
    -(IBAction)playSound:(id)sender {
         NSString *soundFile = [[NSBundle mainBundle] pathForResource:@"Hello" ofType:@"wav"];
         AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:soundFile] error:nil];
         [soundsArray addObject:audioPlayer];
         [audioPlayer prepareToPlay];
         [audioPlayer play];
      }
    

    That should do what you need.

    0 讨论(0)
提交回复
热议问题