【问题标题】:Play NSSound two times播放两次 NSSound
【发布时间】:2012-03-19 16:36:00
【问题描述】:

我想播放 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.*/

谁能告诉我这个错误的原因是什么? 我该如何处理?

我还有其他方法吗?

【问题讨论】:

  • 好像你正在使用垃圾收集。如果可能的话,你应该把你的代码移到 ARC 上,很多框架在启用 GC 时有点脆弱。
  • 我必须做些什么才能让 ARC 工作并禁用 GC?我在 ARC 可用之前就开始了这个项目......
  • 新的 Xcode 4.3.1 在 Edit > Refactor 菜单下自动将项目从 GC 转换为 ARC。
  • 好的,谢谢... 这样做修复了来自 GC 的消息,但没有修复声音播放问题。但是...我找到了导致问题的原因:)

标签: objective-c cocoa


【解决方案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);
}

我发现即使声音已经结束,我也必须在开始第二个之前调用 [sound stop]。

【讨论】:

    【解决方案2】:

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

    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];
    

    【讨论】:

    • 可能有效,但我仍然得到“malloc: *** auto malloc[589]: error: GC operation on unregistered thread。线程隐式注册。中断 auto_zone_thread_registration_error() 进行调试。”应该播放第二个时的消息...所以第二个没有声音...
    • 该错误消息只是关于垃圾收集的警告,已在 10.6 中添加,不应成为问题。这是您无法控制的Apple must resolve 的错误。在整个框架中都有这样的几个,尤其是在 64 位版本的框架之上的 32 位代码中。
    • 但是第二个声音没有播放...我可以听第一个但第二个不见了...
    • 在我的系统上运行代码就像一个魅力。会不会是你的声音超过10秒?添加 "NSLog(@"Duration: %f", [声音持续时间]);"找出你的声音有多长。如果是这种情况,您想为等待量添加一个最小值,我编辑了代码以添加等待。否则,这是 init 的错误,因为我使用“[NSSound soundNamed:@"Morse"]”来测试上述代码。
    • 声音大约 6.04 秒长...我也试过 soundNamed:@"MessageArrived" ,它再次适用于第一次播放,但不适用于第二次...这是怎么回事...
    猜你喜欢
    • 1970-01-01
    • 2012-03-15
    • 2012-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-24
    • 1970-01-01
    相关资源
    最近更新 更多