声音选择器/系统声音列表

jak*_*981 4 macos xcode cocoa system-sounds nssound

好的.我正在寻找一种简洁的方法来列出使用[NSSound soundNamed:]播放的系统声音 - 对我而言似乎API没有可用声音列表.

我还用谷歌搜索了这个,发现了一些相当古老且部分已被弃用的资源.如果应用程序应该有一个声音拾取器 - 什么是获得系统提供的声音列表的最佳方法?

jak*_*981 10

这是我的实施.

NSSound(systemSounds.h):

#import <AppKit/AppKit.h>

@interface NSSound (systemSounds)

+ (NSArray *) systemSounds;

@end
Run Code Online (Sandbox Code Playgroud)

NSSound(systemSounds.m):

#import "NSSound (systemSounds).h"

@implementation NSSound (systemSounds)

static NSArray *systemSounds = nil;

+ (NSArray *) systemSounds
{
    if ( !systemSounds )
    {
        NSMutableArray *returnArr = [[NSMutableArray alloc] init];
        NSEnumerator *librarySources = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSAllDomainsMask, YES) objectEnumerator];
        NSString *sourcePath;

        while ( sourcePath = [librarySources nextObject] )
        {
            NSEnumerator *soundSource = [[NSFileManager defaultManager] enumeratorAtPath: [sourcePath stringByAppendingPathComponent: @"Sounds"]];
            NSString *soundFile;
            while ( soundFile = [soundSource nextObject] )
                if ( [NSSound soundNamed: [soundFile stringByDeletingPathExtension]] )
                    [returnArr addObject: [soundFile stringByDeletingPathExtension]];           
        }

        systemSounds = [[NSArray alloc] initWithArray: [returnArr sortedArrayUsingSelector:@selector(compare:)]];
        [returnArr release];
    }
    return systemSounds;
}

@end
Run Code Online (Sandbox Code Playgroud)

可自由使用,可供任何人用于任何目的,如果你增强它,请分享:)

  • @Gik` [[NSSound soundNamed:@"Glass"] play];` (2认同)