2011-04-10 3 views
0

Xcode를 처음 사용하고 문제가 있습니다. 소리 단추를 여러 번 클릭하면 서로 겹치게됩니다. 사운드가 재생되는 동안 버튼을 클릭하면 현재 사운드가 멈추고 새 사운드가 시작되도록 코드를 어떻게 설정합니까?새 소리 버튼을 눌렀을 때 소리를 멈추는 방법

코드를 게시 할 수 있다면 많은 도움이 될 것입니다.

#import "Sound3ViewController.h" 

@implementation Sound3ViewController 

-(IBAction)playnow:(id)sender;{ 
soundFile = [NSURL fileURLWithPath:[[NSBundle mainBundle] 
            pathForResource:@"winning" 
            ofType:@"mp3"]]; 

sound = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFile error:nil]; 
    sound.delegate = self; 
    [sound play]; 

} 

- (IBAction)play2:(id)sender { 
soundFile = [NSURL fileURLWithPath:[[NSBundle mainBundle] 
             pathForResource:@"onadrug" 
             ofType:@"mp3"]]; 

sound = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFile error:nil]; 
    sound.delegate = self; 
    [sound play]; 


} 

- (void)dealloc 
{ 
    [super dealloc]; 
    [sound release]; 
    [super dealloc]; 
} 

- (void)didReceiveMemoryWarning 
{ 
    // Releases the view if it doesn't have a superview. 
    [super didReceiveMemoryWarning]; 

    // Release any cached data, images, etc that aren't in use. 
} 

#pragma mark - View lifecycle 

/* 
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib. 
- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
} 
*/ 

- (void)viewDidUnload 
{ 
    [super viewDidUnload]; 
    // Release any retained subviews of the main view. 
    // e.g. self.myOutlet = nil; 
} 

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation 
{ 
    // Return YES for supported orientations 
    return (interfaceOrientation == UIInterfaceOrientationPortrait); 
} 


@end 

답변

0

내가 변수로 소리를 재생 허용하고 이후에 다시 허용하는 조치를 예약 할 수 제안 :

감사합니다, 도미닉 여기

내 현재 코드의 복사본입니다 파일의 지속 기간. 예 :

boolean allowed = true 

-(IBAction)playnow:(id)sender 
{ 
    if (allowed) { // <--- ADD THIS 
    allowed = false; 
    soundFile = [NSURL fileURLWithPath:[[NSBundle mainBundle] 
            pathForResource:@"winning" 
            ofType:@"mp3"]]; 
    sound = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFile error:nil]; 
    sound.delegate = self; 
    [sound play]; 

    NSInvocation *invocation = [[NSInvocation alloc] init]; 
    [invocation setTarget:self]; 
    [invocation setSelector:@selector(allowPlaying)]; 
    [NSTimer scheduledTimerWithTimeInterval:[sound duration] invocation:invocation repeats:NO]; 
    } // <-- AND THIS 
} 
-(void)allowPlaying 
{ 
    allow = true; 
} 

바로 즉석에서 쓴하지만 당신은 일반적인 생각을 가지고 있기 때문에 그것을 테스트하지 않았나요 ..

+0

감사 잭,하지만 난 몇 가지 오류 메시지를받은 : 정확하지만,이 시도. 온라인 - (IBAction) playnow : (id) 보낸 사람 여기에 (함수가 아닌) "예상 표현", "playnow", "Expireded"또는 ";"라는 오류 메시지가 나타납니다. before : "토큰과 온라인 : allow = true; 난 오류가 발생했습니다 : "허용"undecalred (이 함수에서 처음 사용) – Dominick

+0

물론, 부울 허용 = true' 세미콜론 (;)없이 쓴 이후 그냥 추가하십시오. 당신은 Obj-C 문법으로는 그렇게 실용적이지 않습니다. :)'allow '에 대해 신경 쓰지 않았습니다. C 파일이나 내부 객체 자체를 속성으로 저장하도록 선택해야하기 때문입니다. – Jack

+0

잭, 너의 권리, 나는 목표 C를 배우려고 노력하고있다. :) – Dominick

0

나는 또한 objC에 새로 온 사람, 그래서 이것이 확실하지 않다 내가 업데이트 된 코드와 내 원래을 PlayNow 버튼 코드를 대체

#import "Sound3ViewController.h" 

@implementation Sound3ViewController 

-(IBAction)playnow:(id)sender;{ 
    soundFile = [NSURL fileURLWithPath:[[NSBundle mainBundle] 
            pathForResource:@"winning" 
            ofType:@"mp3"]]; 

    // NEW STUFF 
    if (sound) { 
     if ([sound playing]) { 
      [sound stop]; 
     } 
     [sound release]; 
    } 

    sound = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFile error:nil]; 
    sound.delegate = self; 
    [sound play]; 
} 

- (IBAction)play2:(id)sender { 
    soundFile = [NSURL fileURLWithPath:[[NSBundle mainBundle] 
             pathForResource:@"onadrug" 
             ofType:@"mp3"]]; 

    if (sound) { 
     if ([sound playing]) { 
      [sound stop]; 
     } 
     [sound release]; 
    } 

    sound = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFile error:nil]; 
    sound.delegate = self; 
    [sound play]; 


} 

- (void)dealloc 
{ 
    [super dealloc]; 
    if (sound) { 
     [sound release]; 
    } 
} 

- (void)didReceiveMemoryWarning 
{ 
    // Releases the view if it doesn't have a superview. 
    [super didReceiveMemoryWarning]; 

    // Release any cached data, images, etc that aren't in use. 
} 

#pragma mark - View lifecycle 

/* 
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib. 
- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
} 
*/ 

- (void)viewDidUnload 
{ 
    [super viewDidUnload]; 
    // Release any retained subviews of the main view. 
    // e.g. self.myOutlet = nil; 
} 

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation 
{ 
    // Return YES for supported orientations 
    return (interfaceOrientation == UIInterfaceOrientationPortrait); 
} 


@end 
+0

감사 합니다만, 몇 줄의 오류가 발생했습니다 : if ([소리 재생]) 시맨틱 문제 : 메서드 '재생'을 찾을 수 없습니다 (반환 형식의 기본값은 'id') 및 온라인 : if ([소리 재생]) ' AVAudioPlayer '가'-playing '에 응답하지 않을 수 있습니다. – Dominick

+0

'if ([sound isPlaying])'이어야한다고 생각합니다. – MusiGenesis

+0

... 아니면 if (sound.playing)도 효과가 있다고 생각합니다.어떤 이유로 든 objC는 다른 언어가 다소 비슷하게 취급하는 특정 구문 (속성 대 메서드)에 대해 까다로 우며 따라서 이러한 종류의 문제가 많이 발생합니다. – MusiGenesis

0
// in .h file 

#import "AVFoundation/AVAudioPlayer.h" 
//set delegate 
@interface SamplesoundViewController : UIViewController <AVAudioPlayerDelegate>{ 
AVAudioPlayer *player1; 
    AVAudioPlayer *player2; 
... 
... 
} 
@property (nonatomic, retain) AVAudioPlayer *player1; 
@property (nonatomic, retain) AVAudioPlayer *player2; 
-(IBAction)soundfirst; 
-(IBAction)soundsecond; 
-(IBAction)Newmethodname; 



// in .m file 
@implementation SamplesoundViewController 

@synthesize player1,player2; 

-(IBAction)soundfirst{ 
    NSString *path = [[NSBundle mainBundle] pathForResource:@"soundfilefirst" ofType:@"mp3"]; 
    player1=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL]; 

    player1.delegate=self; 
    [player1 play]; 
    [self performSelector:@selector(soundsecond) withObject:nil afterDelay:0.90]; 
} 



-(IBAction)soundsecond{ 
    [player1 stop]; 

    NSString *path = [[NSBundle mainBundle] pathForResource:@"Soundfilesecond" ofType:@"mp3"]; 

    player2=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL]; 

    player2.delegate=self; 
    [player2 play]; 
    [self performSelector:@selector(Newmethodname) withObject:nil afterDelay:1]; 


} 


-(IBAction)Newmethodname{ 
    [player2 stop]; 
    //write your code here 
} 
관련 문제