2012-08-15 73 views
2

在iOS應用程序中執行其他操作之前,我需要播放3秒左右的短暫聲音(如倒計數嘟嘟聲)。iOS在執行其他動作之前播放聲音

使用情況如下:

用戶點擊一個按鈕...嗶聲播放(使用AudioServicesPlaySystemSound簡單的嗶嗶聲......那麼該方法的其餘部分運行

我似乎無法。找到一個方法來阻止我的方法,而音播放

我已嘗試以下步驟:

[self performSelector:@selector(playConfirmationBeep) onThread:[NSThread currentThread] withObject:nil waitUntilDone:YES]; 

在音色播放同步WH執行其餘的方法。

上述呼叫我錯過了什麼?

回答

2

AudioServicesPlaySystemSound是異步的,所以你不能阻止它。您想要做的是讓音頻服務在播放完成時通知您。你可以通過AudioServicesAddSystemSoundCompletion來做到這一點。

這是一個C級API這樣的事情是有點難看,但你可能想要的東西,如:

// somewhere, a C function like... 
void audioServicesSystemSoundCompleted(SystemSoundID ssID, void *clientData) 
{ 
    [(MyClass *)clientData systemSoundCompleted:ssID]; 
} 

// meanwhile, in your class' init, probably... 
AudioServicesAddSystemSoundCompletion(
    soundIDAsYoullPassToAudioServicesPlaySystemSound, 
    NULL, // i.e. [NSRunloop mainRunLoop] 
    NULL, // i.e. NSDefaultRunLoopMode 
    audioServicesSystemSoundCompleted, 
    self); 

// in your dealloc, to avoid a dangling pointer: 
AudioServicesRemoveSystemSoundCompletion(
      soundIDAsYoullPassToAudioServicesPlaySystemSound); 

// somewhere in your class: 
- (void)systemSoundCompleted:(SystemSoundID)sound 
{ 
    if(sound == soundIDAsYoullPassToAudioServicesPlaySystemSound) 
    { 
     NSLog(@"time to do the next thing!"); 
    } 
} 

如果你真的想阻止時播放聲音時,並假設UI類是一個視圖控制器,你應該在相應的時間段內關閉self.view.userInteractionDisable。你絕對不想做的是阻止主運行循環;這將阻止重要的系統事件,如低內存警告通過,因此可能導致您的應用程序被強制退出。你也可能還想服從像旋轉設備這樣的東西。