2014-02-06 88 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; 
} 
相关问题