点击按钮播放声音

时间:2012-09-25 05:29:30

标签: iphone

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

- (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]:无法识别的选择器发送到实例0x758c790'”

但是,如果我在其他任何地方播放声音,但没有点击按钮,那么播放没有任何问题。我不知道为什么会发生这种情况?请帮帮我

2 个答案:

答案 0 :(得分: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];
}

答案 1 :(得分: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];

    }