iOS:当用户选择新的选择器时,如何在PickerViewController上自动停止声音文件?

时间:2012-01-03 14:30:48

标签: ios ios4 ios5 uipickerview

我有一个有多个声音的音乐播放器。我的问题是,当我在选择器视图中选择一个对象时,它会自动播放,但是当我选择一个新对象时,旧的声音将不会停止。声音将与新声音重叠。我该如何自动停止?这是我的疑难解答代码:

H档案:

#import <UIKit/UIKit.h>
#import <AVFoundation/AVAudioPlayer.h>

@interface musixGreetingViewController : UIViewController <UIPickerViewDelegate, UIPickerViewDataSource, AVAudioPlayerDelegate>{

    UIPickerView       *picker;
    UILabel            *musicTitle;
    NSMutableArray     *musicList;
    AVAudioPlayer      *audioPlayer;


}


@property (nonatomic, retain) IBOutlet UIPickerView *picker;
@property (nonatomic, retain) IBOutlet UILabel *musicTitle;
@property (nonatomic, retain) NSMutableArray *musicList;

-(IBAction)playSelectedMusic:(id)sender;


@end

M档案:

    - (void)viewDidLoad
    {
        [super viewDidLoad];
         musicList = [[NSMutableArray alloc] initWithObjects:@"m1",@"m2",@"m3",@"m6",@"m4", @"m5",nil];
    }

-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component


{

    //[self playSelectedMusic:self];

    if ([[musicList objectAtIndex:row] isEqual:@"m1"])
    {

        NSString *path = [[NSBundle mainBundle] pathForResource:@"m1" ofType:@"mp3"];
        AVAudioPlayer* theAudio=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];

        pickerView.delegate = self;
        [theAudio play];

        NSString *resultString = [[NSString alloc] initWithFormat:
                                  @"m1",
                                  [musicList objectAtIndex:row]];
        musicTitle.text = resultString;


    }


    if ([[musicList objectAtIndex:row] isEqual:@"m2"])
    {

        NSString *path = [[NSBundle mainBundle] pathForResource:@"m2" ofType:@"mp3"];
        AVAudioPlayer* theAudio=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];

        pickerView.delegate = self;
        [theAudio play];



        NSString *resultString = [[NSString alloc] initWithFormat:
                                  @"m2",
                                  [musicList objectAtIndex:row]];
        musicTitle.text = resultString;


    }

-(IBAction)playSelectedMusic:(id)sender{

I want the music play here, how to do so without autoplay the music in the picker view?

}

1 个答案:

答案 0 :(得分:0)

这会将玩家重置为开头:

[theAudio setCurrentTime:0.0];