How do I make an array of SystemSoundIDs? Using AudioToolbox framework

人走茶凉 提交于 2019-12-12 04:08:11

问题


I'm used to creating sounds like this:

NSString *explosionsoundpath = [[NSBundle mainBundle] pathForResource:@"explosion" ofType:@"caf"];
CFURLRef explosionurl = (CFURLRef ) [NSURL fileURLWithPath:explosionsoundpath];
AudioServicesCreateSystemSoundID (explosionurl, &explosion1a);
AudioServicesCreateSystemSoundID (explosionurl, &explosion1b);  

where explosion1a and explosion1b are instance variables declared in the .h file with:

SystemSoundID explosion1a;

Whenever I try to make this process in an array like this

    NSString *plasmasoundpath = [[NSBundle mainBundle] pathForResource:@"plasmasound" ofType:@"caf"];
CFURLRef plasmaurl = (CFURLRef ) [NSURL fileURLWithPath:plasmasoundpath];
SystemSoundID plasmalaunch1;
AudioServicesCreateSystemSoundID (plasmaurl, &plasmalaunch1);
[self.plasmasounds addObject:plasmalaunch1];

I get a warning:

"Passing argument 1 of addObject makes pointer from integer without a cast.

If I put the & symbol before plasmalaunch1 in the addObject argument I get an

incompatible pointer type warning.

I'm trying to create an array of sound effects which I can later play by calling:

SystemSoundID sound = [self.plasmasounds objectAtIndex:i];
AudioServicesPlaySystemSound(sound);

Advice on how to make this work (or a better way to solve this problem) appreciated!


回答1:


A SystemSoundID is a integer value, not an object; and a pointer to a number is not a pointer to an object.

You could encapsulate the numeric value in an object before storing it in an NSArray, and then later removing the ID number from the object to play the sound. Or you could store the integer value in a C array instead of an NSArray.




回答2:


This is old, but still relevant. The best solution is to create a class with a constructor that takes a SystemSoundID argument. This allows maximum flexibility. Now you have an object that can easily be added to NSArray or any other collection class.

    #import <Foundation/Foundation.h>
@import AudioToolbox;

@interface SATSound : NSObject
@property (nonatomic)SystemSoundID id;
- (id)initWithSoundID:(SystemSoundID)id;
@end

/////

#import "SATSound.h"

@implementation SATSound
- (id)initWithSoundID:(SystemSoundID)id
{
    if (self = [super init]) {
        _id = id;
    }
    return self;
}

Just instantiate this class, pass it your SystemSoundID, add the object/instance to an array, and then you can pull out the values with ease and not have to worry about type conversions. You can also add any other properties that might come in handy such as the name of the sound file.



来源:https://stackoverflow.com/questions/3592989/how-do-i-make-an-array-of-systemsoundids-using-audiotoolbox-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!