2013-07-04 84 views
0

我是一個絕對的初學者,在objective-c和其他環境中,請耐心等待。這是我的問題:我需要播放聲音文件,以便每個聲音文件在另一個聲音文件啓動時停止,現在它們重疊;這裏是我的代碼片段。 預先感謝您,讓我知道您是否需要其他細節。第二次播放時停止第一個聲音

- (IBAction)soundfirst { 
    NSString *path = 
     [[NSBundle mainBundle] pathForResource:@"hi2" ofType:@"mp3"]; 

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

    player1.delegate = self; 
    [player1 play]; 
} 
- (IBAction)soundsecond { 
    [player1 stop]; 

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

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

    player2.delegate = self; 
    [player2 play]; 
} 

回答

1

做的時候,你就完蛋了東西的最好方法,就是尋找到的文檔。

在您的代碼中,您正在創建一個類型爲AVAudioPlayer的對象,並將其命名爲player1。

AVAudioPlayer文檔: http://developer.apple.com/library/ios/#DOCUMENTATION/AVFoundation/Reference/AVAudioPlayerClassReference/Reference/Reference.html

看看下實例方法,並有一個有所謂的停止方法。

所以在第一種方法,你可以這樣做

if(player2.playing){ 
    [player2 stop]; 
} 

[player1 play]; 
+0

非常感謝你,我會試着去看看它是否有效。儘管如此,謝謝你。 –

+0

聽起來不錯,讓我知道如果有任何問題。 –

+0

嗨再次Khanh,抱歉打擾你,但我現在有一個新問題:昨天你的解決方案工作,但我想讓代碼更簡單,更少混亂。所以現在當我嘗試使用「if」時有這個問題:使用未聲明的標識符「playsound2」。我可以在哪裏發佈代碼而不會產生新的問題?先謝謝你。 N. –

0
#import <AudioToolbox/AudioServices.h> 

SystemSoundID buttonClickSoundID; 

+ (void)playButtonClickSound { 
    if (buttonClickSoundID == 0) { 
     NSString *soundPath = [[NSBundle mainBundle] pathForResource:@"button_click" ofType:@"wav"]; 
     CFURLRef soundURL = (CFURLRef)[NSURL fileURLWithPath:soundPath]; 
     AudioServicesCreateSystemSoundID(soundURL, &buttonClickSoundID); 
    } 
    AudioServicesPlaySystemSound(buttonClickSoundID); 
} 
+0

像這樣 – Anton

+0

感謝@Anton我現在似乎已經解決了這個問題。祝你有個愉快的日子/晚上 –

相關問題