2013-04-07 153 views
0

1個按鈕,播放10個聲音? 如何獲得按鈕以便按順序播放一些聲音?1個按鈕,播放10個聲音?

如何爲此操作添加額外的聲音?

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

難道你知道所有的聲音的持續時間? – 2013-04-07 14:38:41

+0

爲什麼不連接音頻文件並播放一個文件? ;) – HAS 2013-04-08 17:56:59

+0

2-3秒。 我想做一個計數應用程序,所以在第一次觸摸它說1和第二次觸摸2.等等... – 2013-04-14 00:04:26

回答

0

我有最好的運氣AVAudioPlayer - 這是一個叫AVFoundation庫,您可以通過「構建階段」導入(第一次點擊左上方的藍色Xcode項目名稱),然後選擇「鏈接二進制與圖書館「

那就試試這個非常簡單的YouTube教程做一個按鈕播放聲音:

http://youtu.be/kCpw6iP90cY

這是我用了2年前創造我的第一個音板相同的視頻。 Xcode 5有點不同,但代碼都可以工作。

好的,現在你需要創建一個這些聲音的數組,它們將循環通過它們。從樹屋看看這個鏈接:

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

+0

我不能upvote答案,因爲我不熟悉的主題,但如果你發佈一個鏈接到你想插入的圖片,我可以爲你插入它。 – 2014-01-07 23:45:10

0

如果聲音是名sound0 ... soundN,你可以介紹給高德 - 一個跟蹤當前索引,一個定義聲音的數量。

@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