iphone - 多次按下时声音重叠

标签 iphone ios4 memory audio

当我按下一个按钮,然后再按下另一个按钮时,声音会重叠。如何解决该问题,以便在按下另一个声音时停止播放第一个声音?

 - (void)playOnce:(NSString *)aSound {

NSString *path = [[NSBundle mainBundle] pathForResource:aSound ofType:@"caf"];
AVAudioPlayer* theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
[theAudio setDelegate: self];
[theAudio setNumberOfLoops:0];
[theAudio setVolume:1.0];
[theAudio play];    
 }

- (void)playLooped:(NSString *)aSound {

NSString *path = [[NSBundle mainBundle] pathForResource:aSound ofType:@"caf"];
AVAudioPlayer* theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
[theAudio setDelegate: self];
// loop indefinitely
[theAudio setNumberOfLoops:-1];
[theAudio setVolume:1.0];
[theAudio play];
[theAudio release];


    }

最佳答案

在viewController的标题中声明您的AVAudioPlayer(每次播放声音时不要分配一个新的)。这样,您将拥有可以在StopAudio方法中使用的指针。

@interface myViewController : UIViewController <AVAudioPlayerDelegate> { 
    AVAudioPlayer *theAudio;
}
@property (nonatomic, retain) AVAudioPlayer *theAudio;
@end


@implementation myViewController
@synthesize theAudio;
- (void)dealloc {
    [theAudio release];
}
@end



- (void)playOnce:(NSString *)aSound {
    NSString *path = [[NSBundle mainBundle] pathForResource:aSound ofType:@"caf"];
    if(!theAudio){
        theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL: [NSURL fileURLWithPath:path] error:NULL];
    }
    [theAudio setDelegate: self];
    [theAudio setNumberOfLoops:0];
    [theAudio setVolume:1.0];
    [theAudio play];
}

- (void)playLooped:(NSString *)aSound {
    NSString *path = [[NSBundle mainBundle] pathForResource:aSound ofType:@"caf"];
    if(!theAudio){
        theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL: [NSURL fileURLWithPath:path] error:NULL];
    }
    [theAudio setDelegate: self];
    // loop indefinitely
    [theAudio setNumberOfLoops:-1];
    [theAudio setVolume:1.0];
    [theAudio play];
}

- (void)stopAudio {
    [theAudio stop];
    [theAudio setCurrentTime:0];
}

还请务必阅读Apple Docs

关于iphone - 多次按下时声音重叠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8101718/

相关文章:

ios - 使用 Xcode Instruments 查看指针处的非僵尸对象历史记录

ios - 通过任何设备上的链接安装 ios 应用程序(不知道设备的 udid)?

iphone - Swift:如何以编程方式设置 iphone 音量

ios - 以编程方式停止向 iPhone 发送短信

objective-c - 自定义 iPhone 主页按钮的 Action 以在 gamecenter 中提交分数

iphone - 更改 .xcdatamodeld 文件中 .xcdatamodel 条目的顺序

iPhone UIDatePicker 设置MaximumDate

iphone - 如何在 UITapGestureRecognizer 中的 @selector 中传递参数?

c - 内存中的值如何与变量及其类型相关联?

memory - 现代 GPU 上纹理内存的最大大小是多少?