从您在问题中包含的几个代码片段中,您似乎正在这样做:
// create new sound object
NSSound *sound = [[NSSound alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"ping" ofType:@"aiff"] byReference:NO];
// start it playing
[sound play];
然后你创建另一个新的声音对象:
// create new sound object
NSSound *sound = [[NSSound alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"ping" ofType:@"aiff"] byReference:NO];
// this cannot be true - you just created the sound object
if([sound isPlaying]) {
[sound stop];
}
试试这个非常简单的例子(只需将播放和停止按钮添加到视图控制器并连接它们):
#import "ViewController.h"
@interface ViewController() {
NSSound *sound;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// instantiate sound object with file from bundle
sound = [[NSSound alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"1162" ofType:@"aiff"] byReference:NO];
}
- (IBAction)playClicked:(id)sender {
if (sound) {
[sound play];
}
}
- (IBAction)stopClicked:(id)sender {
if (sound && [sound isPlaying]) {
[sound stop];
}
}
- (void)setRepresentedObject:(id)representedObject {
[super setRepresentedObject:representedObject];
}
@end