NSSound停止功能

NSSound stop function

感谢您的帮助。

这将激活引用文件的基本播放:

NSSound *sound = [[NSSound alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"ping" ofType:@"aiff"] byReference:NO];

[sound play];

结束播放的正确方法是什么?执行以下操作不走运:

NSSound *sound = [[NSSound alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"ping" ofType:@"aiff"] byReference:NO];

if([sound isPlaying])  {
    
    [sound stop];

感谢您的帮助。

根据您在问题中包含的几个代码片段,看起来您正在这样做:

// 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