-1

我面临一个非常奇怪的问题,我的要求是在单击按钮时播放声音,这是我的代码:

- (void)viewDidLoad
{
    [super viewDidLoad];    
    NSString *path=[[NSBundle mainBundle] pathForResource:@"button-3" ofType:@"mp3"];
    tapSound=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL]];
    [tapSound prepareToPlay];
    tapSound.delegate=self;

    //creating the button in view did load and button is declared in .h
    btn=[UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame=CGRectMake(x, y, 58,58);
    [btn addTarget:self action:@selector(btnClkd:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];
}

//click method
-(void)btnClkd:(UIButton*)sender
{
[tapSound play];
}

但是当我运行代码并单击按钮时,我的应用程序崩溃并出现此错误:“由于未捕获的异常 'NSInvalidArgumentException' 而终止应用程序,原因:'-[UIButton play]: unrecognized selector sent to instance 0x758c790'”

但是,如果我在其他任何地方播放声音而不是单击按钮,那么它会毫无问题地播放。我不知道为什么会这样?请帮我

4

2 回答 2

2

做这个:

-(void)btnClkd:(UIButton*)sender
{
   NSString *path=[[NSBundle mainBundle] pathForResource:@"button-3" ofType:@"mp3"];
   tapSound = nil;
   tapSound=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL]];
   [tapSound prepareToPlay];
   tapSound.delegate=self;
   [tapSound play];
}
于 2012-09-25T05:34:00.673 回答
0

试试这个。添加你的 .h 文件

 .h file 



         #import <AVFoundation/AVFoundation.h>
            #import <AudioUnit/AudioUnit.h>


        AVAudioPlayer *player1;

        @property(nonatomic ,retain)AVAudioPlayer *player1;

in your .m file 




@synthesize  player1;



    - (void)viewDidLoad
        {
            [super viewDidLoad];    

 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];    
            NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:@"button-3" ofType:@"mp3"];    
            NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:soundFilePath];    
            AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:nil];    
            [fileURL release]; 
            self.player1 = audioPlayer;    
            [audioPlayer release]; 
           [self.player1 prepareToPlay];
          [self.player1 setDelegate:self];
           [pool release]; 

            //creating the button in view did load and button is declared in .h
            btn=[UIButton buttonWithType:UIButtonTypeCustom];
            btn.frame=CGRectMake(x, y, 58,58);
            [btn addTarget:self action:@selector(btnClkd:) forControlEvents:UIControlEventTouchUpInside];
            [self.view addSubview:btn];
        }




    -(void)btnClkd:(UIButton*)sender {            

            [self.player1 play];

    }
于 2012-09-25T05:47:47.883 回答