开发者

Overlapping of sounds

开发者 https://www.devze.com 2023-03-30 10:02 出处:网络
Why do my music overlap? Is there any way to play it one by one? - (void)viewDidLoad { [super viewDidLoad];

Why do my music overlap? Is there any way to play it one by one?

- (void)viewDidLoad
{
[super viewDidLoad];
NSMutableArray *array = [NSMutableArray array];
[array insertObject: [[NSBundle mainBundle] pathForResource:@"Master of Puppets" ofType:@"mp3"] atIndex:0];
[array insertObject: [[NSBundle mainBundle] pathForResource:@"music" ofType:@"mp3"] atIndex:1];
[array insertObject: [[NSBundle mainBundle] pathForResource:@"Start" ofType:@"caf"] atIndex:2];
[array insertObject: [[NSBundle mainBundle] pathForResource:@"thx" ofType:@"m4v"] atIndex:3];
[array insertObj开发者_运维百科ect: [[NSBundle mainBundle] pathForResource:@"sound" ofType:@"aif"] atIndex:4];

for (int i=0; i < [array count]; i++)
{
theAudio=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:[array objectAtIndex:i]] error:NULL]; 
theAudio.delegate = self;
[theAudio prepareToPlay];
[theAudio play];       
}

}

in .h:

@interface STAMP_AudioViewController : UIViewController <AVAudioPlayerDelegate>{
AVAudioPlayer* theAudio;
}

@end


Implement audioPlayerDidFinishPlaying delegate from AVAudioPlayerDelegate and start second song from there...

NSMutableArray *array ;
int index = 0;

- (void)viewDidLoad
{
  [super viewDidLoad];
  NSMutableArray *array = [NSMutableArray array];
  [array insertObject: [[NSBundle mainBundle] pathForResource:@"Master of Puppets" ofType:@"mp3"] atIndex:0];
  [array insertObject: [[NSBundle mainBundle] pathForResource:@"music" ofType:@"mp3"] atIndex:1];
  [array insertObject: [[NSBundle mainBundle] pathForResource:@"Start" ofType:@"caf"] atIndex:2];
  [array insertObject: [[NSBundle mainBundle] pathForResource:@"thx" ofType:@"m4v"] atIndex:3];
  [array insertObject: [[NSBundle mainBundle] pathForResource:@"sound" ofType:@"aif"] atIndex:4];

  theAudio=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:[array  objectAtIndex:index]] error:NULL]; 
  theAudio.delegate = self;
  [theAudio prepareToPlay];
  [theAudio play]; 

  index++;      
}

Now player plays first song..And below given delegate will fire after song is completed..then play second song..Remember you have to release the first player and initialize new AVAudioPlayer and init with second song..

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag{
  [theAudio release];

  if(index > 4)//your array highest index
    return;

  theAudio=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:[array  objectAtIndex:index]] error:NULL]; 
  theAudio.delegate = self;
  [theAudio prepareToPlay];
  [theAudio play];

  index++;
}

This logic should work..I cant find any function in AVAudioPlayer to change the song after initializing..So we need to create new object..:(

0

精彩评论

暂无评论...
验证码 换一张
取 消