我正在尝试制作音频控制器,但停止按钮不起作用。但我不知道为什么。这是怎么造成的,我该如何解决?
.h
#import <UIKit/UIKit.h>
#import <AVFoundation/AVAudioPlayer.h>
@interface myprojectViewController : UIViewController {
AVAudioPlayer* theAudio;
}
- (IBAction)start:(id)sender;
- (IBAction)stop:(id)sender;
@end
.m
- (IBAction)start:(id)sender{
NSString *path = [[NSBundle mainBundle] pathForResource:@"LE" ofType:@"wav"];
AVAudioPlayer* theAudio=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
theAudio.delegate = self;
[theAudio play];
}
- (IBAction)stop:(id)sender{
[theAudio stop];
}
答案 0 :(得分:0)
'theAudio'是start()方法中的局部变量。您已将其声明为局部变量,因此它在stop()方法中超出范围,并且您的引用无效。您需要使用类变量'theAudio。变化:
AVAudioPlayer* theAudio=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
到
self.theAudio=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];