2014-09-20 134 views
0

我在嘗試提出解決方案以解決我的問題方面做了大量的閱讀和研究工作,似乎無法讓我的代碼按照我想要的方式工作,或者應該如此。我想要做的是,如果我決定在另一個聲音按鈕的音頻結束之前點擊另一個聲音按鈕,則可以使不同的按鈕播放不同的短音,而不會互相重疊。我已經成功地使用SystemSoundID播放他們指定的聲音,但當我點擊多個buttons時,它們仍然重疊。Xcode中的音頻重疊

下面是我的代碼示例:

接口文件:

#import <AVFoundation/AVFoundation.h> 
#import <UIKit/UIKit.h> 

@interface ViewController : UIViewController { 
} 

-(IBAction)Sound:(id)sender; 

@end 

實現文件:

#import "ViewController.h" 
#import <AVFoundation/AVFoundation.h> 
#import <UIKit/UIKit.h> 


@implementation ViewController : UIViewController 

- (IBAction)Sound:(id)sender 
{ 
    NSString *path = [[NSBundle mainBundle] pathForResource:@"Sound" ofType:@"mp3"]; 
    AVAudioPlayer* theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL]; 
    [theAudio play]; 
} 

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
} 

- (void)didReceiveMemoryWarning 
{ 
    [super didReceiveMemoryWarning]; 
} 

@end 

我希望幫助更多比你知道的,因爲我已經花了相當一段時間試圖讓它按照應有的方式工作。如果您有任何問題,請告訴我!非常感謝你。

-Michael

回答

0

我的理解,當你發揮AudioSystemSound,它將發揮,直到完成。這種播放音頻的方法並不是一個功能強大的方法,只能用於簡單的「點擊」和「調音」等。對於更全面的音頻套件功能,您可以在AVAudioPlayer中使用AVFoundation庫你可以調用「停止」來停止播放被叫聲音。

https://developer.apple.com/av-foundation/

編輯除了上述的答案:

在您的.h文件中請務必包括:

@import AVFoundation; 

然後創建一個AV播放器;

AVAudioPlayer *playAudio 

在您的.m文件中在需要播放聲音的方法中添加以下代碼塊。當然,適當地調整歌曲/音頻名稱和格式;

NSString *backgroundMusic = [[NSBundle mainBundle] 
          pathForResource:@"insertSongNameHere" ofType:@"mp3"]; 

playAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:insertSongNameHere] error:NULL]; 
playAudio.numberOfLoops = -1; 
[playAudio play]; 

注意:循環次數爲-1意味着永久重複。當然,你可以做任何你喜歡的數字。我希望所有的幫助,如果不讓我知道,我會看看我能做些什麼來協助!

+0

非常感謝Frankeex的反饋。我使用AVAudioPlayer編輯了上面的代碼,但由於某種原因聲音不再播放,我不知道爲什麼。 – Michael 2014-09-29 04:15:58

+0

@邁克爾 - 我編輯我的答案上面更具體的幫助。希望能讓你走。 – Frankeex 2014-09-29 10:13:56

+0

有一些輕微的調整,這完美的工作!再次感謝Frankeex,我真的很感謝幫助。 – Michael 2014-10-01 02:39:11