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/8100531/

相关文章:

iphone - 当我在 Swift 中销毁我的对象时,它不会释放我的 RAM 内存

iphone - 卡号前 12 位数字应安全输入,其余 4 位数字正常

iphone - NSXMLParser initWithContentsOfURL 超时

iphone - 如何在 TableViewController 上方添加 UIView

iphone - 如何在调整 UIView 大小时设置动画

iPhone 等同于周期性任务的 Timer 和 TimerTask

Java 进程内存无限增长。内存泄漏?

ios - SKSpriteNode 使用 UIColor 设置颜色

ios - 如何修复文件中缺少的必需架构 i386?

java - scala vs java,性能和内存?