使用播放它的相同按钮停止声音 [英] Stop a sound using the same button that plays it

查看:138
本文介绍了使用播放它的相同按钮停止声音的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很简单,我使用一个按钮生成一个随机数,然后用开关/箱,它动画图像和播放声音。我的问题是,当您再次按下按钮时,之前播放的声音不会停止,声音会重叠。

Pretty simple, I'm using one button that generates a random number and then with a switch/case, it animates an image and plays a sound. My problem is that when you press the button again, the sound that was playing before doesn't stop and the sound overlaps.

以下是代码:

- (IBAction) pushme: (id) sender{
int random = (arc4random()%10);
switch (random) {
    case 0:  {
            [ANIMATION NUMBER 0]

            NSString *path = [NSString stringWithFormat:@"%@%@",[[NSBundle mainBundle] resourcePath],@"/sound0.wav"];
            SystemSoundID soundID;
            NSURL *filePath = [NSURL fileURLWithPath:path isDirectory:NO];
            AudioServicesCreateSystemSoundID((CFURLRef)filePath, &soundID);
            AudioServicesPlaySystemSound(soundID);
        }
        break;
    case 1:  {
            [ANIMATION NUMBER 1]

            NSString *path = [NSString stringWithFormat:@"%@%@",[[NSBundle mainBundle] resourcePath],@"/sound1.wav"];
            SystemSoundID soundID;
            NSURL *filePath = [NSURL fileURLWithPath:path isDirectory:NO];
            AudioServicesCreateSystemSoundID((CFURLRef)filePath, &soundID);
            AudioServicesPlaySystemSound(soundID);
    } break; //Lots more cases after this one

我知道这不是最好的方法,反复声明相同的变量。
但是有一种方法来阻止它之前它玩另一个?

I know that this is not the best way to do it, declaring the same variable over and over. but is there a way to stop it before it plays another one?

推荐答案

我刚刚回答了我自己的问题。

I just dicovered the answer to my own question.

我所做的是


  1. 声明 SoundSystemID soundID ;

  2. 在生成随机数之前添加此行: AudioServicesDisposeSystemSoundID(soundID);

  1. Declare SoundSystemID soundID; in the header.
  2. Add this line before the random number gets generated: AudioServicesDisposeSystemSoundID(soundID);

请记住,如果您要再次播放声音,则需要在处理完毕后重新加载资源。

Remember that if you are going to play the sound again, you will need to load the resource again after disposing of it.

谢谢你们。

这篇关于使用播放它的相同按钮停止声音的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆