玩NSSound两次

时间:2012-03-15 08:32:50

标签: objective-c cocoa

我想要播放NSSound两次,除了它短于10秒然后我想等到10秒完成然后开始第二个。

但是我在两次播放相同的NSSound时遇到了问题。

NSString *resourcePath = [[NSBundle mainBundle] pathForResource:@"MessageArrived" ofType:@"wav"];
NSSound *sound = [[NSSound alloc] initWithContentsOfFile:resourcePath byReference:YES];
[sound play] //It plays the fist time
[sound play] //I get the following Error and it doesn't play a secont time
/*malloc: *** auto malloc[498]: error: GC operation on unregistered thread. Thread registered implicitly. Break on auto_zone_thread_registration_error() to debug.*/

有人能告诉我这个错误的原因是什么吗? 我怎么处理这个?

我还有其他办法吗?

2 个答案:

答案 0 :(得分:1)

所以在搜索并尝试解决之后,我得到了解决问题的方法......

NSSound *sound = [NSSound soundNamed:@"MessageArrived"];
BOOL res = [sound play];
NSLog(@"%d", res);
[NSThread detachNewThreadSelector:@selector(playSecondSound:) toTarget:self withObject:sound];

-(void)playSecondSound:(NSSound*)sound
{
    [NSThread sleepForTimeInterval:10-[sound duration]];
    [sound stop];
    BOOL res = [sound play];
    NSLog(@"%d", res);
}

我发现即使声音结束,我也必须在开始第二次之前调用[声音停止]。

答案 1 :(得分:0)

当您调用第二个播放方法时,声音已经播放,显然是垃圾收集中的错误,因为第二个播放应该被忽略,但这不会是您想要实现的问题。

NSString *resourcePath = [[NSBundle mainBundle] pathForResource:@"MessageArrived" ofType:@"wav"];
NSSound *sound = [[NSSound alloc] initWithContentsOfFile:resourcePath byReference:YES];
[sound play];

//Will play the second time after 10.0 seconds have passed.
NSInteger wait = ([sound duration] < 10.0) ? 10.0 - [sound duration] : 0.0; 
[sound performSelector:@selector(play) withObject:nil afterDelay:wait];