0

谢谢您的帮助。

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

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];

感谢您的帮助。

4

1 回答 1

0

从您在问题中包含的几个代码片段中,您似乎正在这样做:

// 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
于 2020-08-26T18:01:18.000 回答