播放声音单击
我面临一个很奇怪的问题,我的要求是发挥按钮单击声音,这是我的代码:播放声音单击
- (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的发挥]:无法识别的选择发送到实例0x758c790’”
但是如果我播放声音的任何地方否则,但不是在按钮的点击,然后它没有任何问题发挥。我不知道为什么会发生这种情况?请帮我
这样做:
-(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];
}
我知道它会工作,但为什么当我们在视图中定义AVAudioPlayer对象的时候给出了一个问题? –
试试这一个。添加在你的.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];
}
哎维卡斯,它也没有工作 –
它的工作..我的应用 –
我想它在模拟器和它不工作 –
通过分配它来尝试按钮。 我不确定,但只是试试这样。 – Deepak