0

1个按钮,播放10个声音?我怎样才能得到一个按钮来按顺序播放一些声音?

如何为这个动作添加额外的声音?

-(IBAction)sound1 
{
    CFBundleRef mainBundle = CFBundleGetMainBundle();
    CFURLRef soundFileURLRef;
    soundFileURLRef = CFBundleCopyResourceURL(mainBundle, (CFStringRef) @"sound1", CFSTR("wav"), NULL);
    UInt32 soundID;
    AudioServicesCreateSystemSoundID(soundFileURLRef, &soundID);
    AudioServicesPlaySystemSound(soundID);
}
4

2 回答 2

0

如果声音名称为 sound0 ... soundN,您可以只介绍 ivars — 一个跟踪当前索引,一个定义声音的数量。

@implementation MyClass {
    NSUInteger soundIdx; 
    NSUInteger soundCount;
}    

-(instancetype) init //or any other entry point method like viewDidLoad,....
{
    self = [super init];
    if (self) {
        soundCount = 10;
    }
    return self;
}


-(IBAction)sound 
{
    CFBundleRef mainBundle = CFBundleGetMainBundle();
    CFURLRef soundFileURLRef;
    soundFileURLRef = CFBundleCopyResourceURL(mainBundle, (CFStringRef) [NSString stringWithFormat:@"sound%lu", soundIdx], CFSTR("wav"), NULL);
    UInt32 soundID;
    AudioServicesCreateSystemSoundID(soundFileURLRef, &soundID);
    AudioServicesPlaySystemSound(soundID);

    soundIdx = (++soundIdx) % soundCount;

}
@end

如果声音名称不遵循任何特定的命名约定,您可以将它们放在一个数组中

@implementation MyClass {
    NSUInteger soundIdx; 
    NSArray *soundNames;
}    

-(instancetype) init //or any other entry point method like viewDidLoad,....
{
    self = [super init];
    if (self) {
        soundNames = @[@"sound1",@"hello", @"ping"];
    }
    return self;
}


-(IBAction)sound
{
    CFBundleRef mainBundle = CFBundleGetMainBundle();
    CFURLRef soundFileURLRef;
    soundFileURLRef = CFBundleCopyResourceURL(mainBundle, (CFStringRef) soundNames[soundIdx], CFSTR("wav"), NULL);
    UInt32 soundID;
    AudioServicesCreateSystemSoundID(soundFileURLRef, &soundID);
    AudioServicesPlaySystemSound(soundID);

    soundIdx = (++soundIdx) % [soundNames count];

}    
@end
于 2014-01-08T00:02:17.523 回答
0

我在 AVAudioPlayer 上遇到了最好的运气——它是一个名为 AVFoundation 的库,您可以通过“Build Phases”(首先单击左上角的蓝色 xcode 项目名称)然后“Link Binary with Libraries”导入

然后尝试这个非常简单的 YouTube 教程来制作按钮播放声音:

http://youtu.be/kCpw6iP90cY

那是我两年前用来创建我的第一个音板的相同视频。Xcode 5 有点不同,但代码都可以工作。

好的,现在您需要创建一个循环播放这些声音的数组。从 TreeHouse 查看此链接:

https://teamtreehouse.com/forum/creating-an-array-with-mp3-sound-files

于 2014-01-07T23:20:32.440 回答