2011-06-15 66 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]; 

}