2013-07-07 50 views
0

播放聲音文件時出現問題:我有多個按鈕,每個按鈕都與一個聲音文件關聯。例如,當聲音n.1顫動時,我按下按鈕開始聲音n.2,兩個聲音重疊。我想讓每個按鈕在按下時停止其他按鈕播放的音頻。這是我的.h文件和我的.m文件的一部分。我曾嘗試使用「if」,但我收到「使用未聲明的標識符」錯誤。請記住,我是一個絕對的初學者,提前謝謝你。播放多個音頻文件時重疊

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

@interface ViewController : UIViewController <AVAudioPlayerDelegate> {} 

-(IBAction)playSound1; 
-(IBAction)playSound2; 

@end 

@implementation ViewController 

-(IBAction)playSound1{ 
    NSString *path=[[NSBundle mainBundle] pathForResource:@"12-Toxicity" ofType:@"mp3"]; 
    AVAudioPlayer* theAudio=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path]error:NULL]; 
    theAudio.delegate=self; 
    [theAudio play]; 

} 

@end 
+0

你需要到這兩個'AVAudioPlayer's的存儲性能,並呼籲'[self.audio1停止]''中和playSound2'反之亦然...... –

+0

謝謝西門,我怎麼能存儲他們...我想,在.h文件中?我記得做了一些工作,然後我不小心刪除了代碼... –

回答

0

此代碼完成這項工作......並且,作爲獎勵,您的應用只需加載一次音樂文件!

// ViewController.h 

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

@interface ViewController : UIViewController <AVAudioPlayerDelegate> 

@property (strong) AVAudioPlayer* sound1Player; 
@property (strong) AVAudioPlayer* sound2Player; 
- (IBAction)playSound1; 
- (IBAction)playSound2; 

@end 

// ViewController.m 

#import "ViewController.h" 

@implementation ViewController 

- (void)viewDidLoad { 
    NSString *pathOne = [[NSBundle mainBundle] pathForResource:@"12-Toxicity" ofType:@"mp3"]; 
    if (pathOne) { 
     self.sound1Player = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:pathOne] error:NULL]; 
     self.sound1Player.delegate = self; 
    } 

    NSString *pathTwo = [[NSBundle mainBundle] pathForResource:@"13-Psycho" ofType:@"mp3"]; 
    if (pathOne) { 
     self.sound2Player = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:pathTwo] error:NULL]; 
     self.sound2Player.delegate = self; 
    } 
} 

- (IBAction)playSound1 { 
    if (self.sound2Player.playing) 
     [self.sound2Player stop]; 
    [self.sound1Player play]; 
} 

- (IBAction)playSound2 { 
    if (self.sound1Player.playing) 
     [self.sound1Player stop]; 
    [self.sound2Player play]; 
} 

@end 
+0

我很無語......謝謝!晚上或任何時間在你的時區;) –

+0

不用擔心@尼科拉,祝你好運與你的其他項目! :) –