2013-03-12 32 views
2

我正在創建一次播放一個聲音的聲卡應用程序。我希望UIButton能夠阻止所有其他聲音播放,並在點擊時開始播放自己的聲音。我有一臺AVAudioPlayer設置爲播放所有聲音(單擊時更改聲音文件的URL,因爲我一次只想播放一個聲音並不是問題)。我想知道如何停止所有其他聲音並按下按鈕播放聲音,但如果點擊的按鈕是當前正在播放聲音的按鈕,則該按鈕僅會停止聲音。我知道這是可以實現的,通過分開音頻播放器和觸發停止事件,但我想避免複製和粘貼代碼,並保持儘可能高效,再加上我只想/需要一個音頻播放器。這裏是我的代碼:觸發AVAudioPlayer停止所有聲音並播放選擇,除非單擊播放(選定)按鈕時

- (IBAction)play { 
if (audioPlayer.playing == NO) { 
    NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/k.mp3", [[NSBundle mainBundle] resourcePath]]]; 
    NSError *error; 
    [audioPlayer release]; 
    audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error]; 
    audioPlayer.numberOfLoops = 0; 

    AVAudioSession *audiosession = [AVAudioSession sharedInstance]; 
    [audiosession setCategory:AVAudioSessionCategoryAmbient error:nil]; 

    [audioPlayer play]; 
    [start setTitle:@"Stop" forState:UIControlStateNormal]; 
} 
else 
    if (audioPlayer.playing == YES) { 
     [audioPlayer stop]; 
    [start setTitle:@"Start" forState:UIControlStateNormal]; 
    } 
    } 


- (IBAction)play2 { 
if (audioPlayer.playing == NO) { 
    NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/chicken.mp3", [[NSBundle mainBundle] resourcePath]]]; 
    NSError *error; 
    [audioPlayer release]; 
    audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error]; 
    audioPlayer.numberOfLoops = 0; 

    AVAudioSession *audiosession = [AVAudioSession sharedInstance]; 
    [audiosession setCategory:AVAudioSessionCategoryAmbient error:nil]; 

    [audioPlayer play]; 
    [start2 setTitle:@"Stop" forState:UIControlStateNormal]; 
} else 
    if (audioPlayer.playing == YES) { 
     [audioPlayer stop]; 
     [start2 setTitle:@"Start" forState:UIControlStateNormal]; 
    } 
} 

任何幫助表示讚賞。先謝謝你!

回答

3

只是這樣做

-(void)stopAudio{ 

if(audioPlayer && [audioPlayer isPlaying]){ 
    [audioPlayer stop]; 
    audioPlayer=nil; 
} 

} 

而調用這個函數在每次點擊..

- (IBAction)play2 { 
    [self stopAudio]; 

    //Do your Stuffs 
} 
0

當你點擊按鈕停止你的音頻播放器和分配新的歌曲URL,然後播放。當你點擊按鈕播放歌曲時,寫下這段代碼。

if(audioPlayer.isPlaying) 
     [audioPlayer stop];  

AVAudioSession *audioSession = [AVAudioSession sharedInstance]; 
[audioSession setCategory:AVAudioSessionCategoryPlayback error:nil]; 
NSURL *url = [NSURL fileURLWithPath:YourSoundURL]; 
NSError *error; 
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error]; 
audioPlayer.delegate=self; 
[audioPlayer play]; 
[start2 setTitle:@"Stop" forState:UIControlStateNormal]; 
相關問題