2014-02-06 89 views
0

如何通過觸摸一次UICollectionViewCell播放聲音,並使用AVAudioPlayer再次觸摸相同的UICollectionViewCell來停止相同的聲音?使用相同的按鈕播放和停止聲音 - AVAudioPlayer

我的代碼正確播放聲音,但當按下單元格時它不會停止它,它只是從一開始就啓動循環。我當前的代碼如下:

// Sound 
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath { 


// Loop 
int loopOrNot; 
BOOL playing = 0; 

if ([loopArray containsObject:saveFavorite]) // YES 
{ 
    loopOrNot = -1; 


} else { 

    loopOrNot = 0; 

} 
// Play soundeffects 

if (playing==NO) { 
    // Init audio with playback capability 


    // Play sound even in silent mode 
    [[AVAudioSession sharedInstance] 
    setCategory: AVAudioSessionCategoryPlayback 
    error: nil]; 

    NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/%@.wav", [[NSBundle mainBundle] resourcePath], [mainArray objectAtIndex:indexPath.row]]]; 

    NSError *error; 
    audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error]; 
    audioPlayer.numberOfLoops = loopOrNot; 

    if (audioPlayer == nil) { 
     // NSLog([error description]); 
    } 
    else { 
     [audioPlayer play]; 
    } 

    playing=YES; 
} 
else if(playing==YES){ 

[audioPlayer stop]; 


    playing=NO; 
} 
} 

回答

1

這裏有一個快速的方法來做到這一點(使用雨燕2.0 FYI) 。將計數器定義爲全局變量並將其設置爲0.再次按下按鈕時,停止音頻並重置其開始時間。希望這可以幫助。

func setupAudioPlayerWithFile(file:NSString, type:NSString) -> AVAudioPlayer { 
    let path = NSBundle.mainBundle().pathForResource(file as String, ofType: type as String) 
    let url = NSURL.fileURLWithPath(path!) 
    var audioPlayer:AVAudioPlayer? 

    do { 
     try audioPlayer = AVAudioPlayer(contentsOfURL: url) 
    } catch { 
     print("NO AUDIO PLAYER") 
    } 

    return audioPlayer! 
} 


@IBAction func buttonTap(sender: AnyObject) { 
    if (counter%2==0) 
    { 
    backMusic = setupAudioPlayerWithFile("Etudes", type: "mp3") 
    backMusic.play() 
    } 
    else 
    { 
     backMusic.stop() 
     backMusic.currentTime = 0.0 
    } 
    counter++ 
1

那是因爲你的playing變量是局部的作用,它的價值是不是在調用保存。每次調用函數時,它都被初始化爲NO。 將該變量移至您的類聲明。

1

在你的方法一開始你設置:

BOOL playing = 0; 

和你的第一個if語句:

if (playing==NO) { 

始終是真實的。

添加到您的方法的開始,之前:

BOOL playing = 0; 

這樣的:

if(playing==YES){ 
    [audioPlayer stop]; 
    playing=NO; 
    return 
} 

而在這之後加入其中設置了播放器的代碼。 在這種情況下,如果玩家正在玩它停止它並從該功能返回,如果它不玩它創建播放器並開始播放。

而且替換此行:

BOOL playing = 0; 

playing = 0; 

,並宣佈這是一個伊娃

@implementation YourClassName 
{ 
    BOOL playing; 
} 
相關問題