我正在尝试制作音频 Controller ,但“停止”按钮不起作用。但是我不知道为什么。这是怎么引起的,我该如何解决?
.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];
}

最佳答案

“theAudio”是start()方法中的局部变量。您已将其声明为局部变量,因此它超出了stop()方法的范围,并且具有无效的引用。您需要使用类变量'theAudio。变更:

AVAudioPlayer* theAudio=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];


self.theAudio=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];

07-26 03:11