2011-06-15 42 views
1

我有一个UIPickerView设置和运行良好。当用户选择一行时,我想让一个音频文件开始播放,但如果用户在第一个音频文件停止播放之前选择另一行,我希望它停止播放,并让新的音频文件播放。 我现在可以用下面的代码来完成它,但是两个文件同时播放,我找不到停止第一个文件的方法。从UIPicker更改音频文件

我正在走错路吗? (我是新来的SDK编码)

任何想法,将不胜感激 感谢

- (NSInteger的)numberOfComponentsInPickerView:(UIPickerView *)thePickerView {

return 1; 

}

- (NSInteger的)pickerView:(UIPickerView *)thePickerView numberOfRowsInComponent:(NSInteger)component { return [list count]; }

- (的NSString *)pickerView:(UIPickerView *)thePickerView titleForRow:(NSInteger的)行forComponent:(NSInteger的)分量{ 返回[列表objectAtIndex:行]。

}

- (无效)pickerView:(UIPickerView *)thePickerView didSelectRow:(NSInteger的)行inComponent:(NSInteger的)分量{ 的NSString *串= [NSString的stringWithFormat:@ “%@”,[列表2 objectAtIndex:行]]; 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]; 


} 

}

回答

2

我没有你的代码测试这一点,但是当我需要做的这一点,我添加了一个简单的检查,看看 是否已经有正在播放的AVAudioPlayer之前停止重新分配。苹果的AVAudioPlayer Class Reference也有很多有用的信息。

// stop sound if already playing 

if (audioPlayer && audioPlayer.isPlaying) { 

    [audioPlayer stop]; 

}