I have a UIPickerView
set up and running fine. When the user selects a row I want one audio file to start but then if the user selects another row before the first audio file has stopped playing I want it to stop the first and just let the new audio file play.
I can do it at present with the code below but both files play at the same time and I cannot find a way of stopping the first one.
Am I going about the wrong way? (I am new to SDK coding)
Any ideas would be appreciated Thanks
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)thePickerView {
return 1;
}
-(NSInteger)pickerView:(UIPickerView *)thePickerView numberOfRowsInComponent:(NSInteger)component{
return [list count];
}
-(NSString *开发者_Python百科)pickerView:(UIPickerView *)thePickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
return [list objectAtIndex:row];
}
-(void)pickerView:(UIPickerView *)thePickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
NSString *string = [NSString stringWithFormat:@"%@", [list2 objectAtIndex:row]];
pickLabel.text = string;
if(row == 1){
NSString *path = [[NSBundle mainBundle]
pathForResource:@"del08sample"ofType:@"mp3"];
AVAudioPlayer* theAudio = [[AVAudioPlayer alloc]
initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
[theAudio play];
}
else if (row == 2){
NSString *path = [[NSBundle mainBundle]
pathForResource:@"icgi03sample"ofType:@"mp3"];
AVAudioPlayer* theAudio = [[AVAudioPlayer alloc]
initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
[theAudio play];
}
}
I haven't tested this with your code, but when I need to do this I add a simple check to see if there is already an AVAudioPlayer that is playing and stop it before re-allocating. Apple's AVAudioPlayer Class Reference has a whole host of useful info too.
// stop sound if already playing
if (audioPlayer && audioPlayer.isPlaying) {
[audioPlayer stop];
}
精彩评论