1个按钮,播放10个声音?

时间:2013-04-07 10:28:46

标签: ios objective-c cocoa-touch button audio

1个按钮,播放10个声音? 如何按顺序播放一些声音按钮?

如何为此动作添加额外声音?

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

2 个答案:

答案 0 :(得分:0)

我在AVAudioPlayer上运气最好 - 它是一个名为AVFoundation的库,您可以通过" Build Phases" (首先点击左上角的蓝色xcode项目名称),然后点击#34; Link Binary with Libraries"

然后试试这个非常简单的YouTube教程,让按钮播放声音:

http://youtu.be/kCpw6iP90cY

这是我2年前用来制作我的第一个音板的视频。 Xcode 5有点不同,但代码都可以工作。

好了,现在你需要创建一个循环遍历这些声音的数组。看看TreeHouse的这个链接:

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

答案 1 :(得分: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