2010-08-13 120 views
2

我是新的iphone和目标c,到目前为止,我已经能够编写一些小例子。播放声音,等待它完成播放并继续(iphone)

我想播放声音,并继续与代码的其余部分在样本播放完毕,即:

printf("hello"); 
playASound["file.wav"]; 
printf("world"); 

其实我越来越:打印你好,播放文件和打印在世界同时 但 我想要的是:打印你好,播放文件,打印世界...... 所以,问题是我如何得到它?

谢谢

btw。这里是playASound代码:

-(void) playASound: (NSString *) file { 

    //Get the filename of the sound file: 
    NSString *path = [NSString stringWithFormat:@"%@/%@", 
         [[NSBundle mainBundle] resourcePath], 
         file]; 

    SystemSoundID soundID; 
    //Get a URL for the sound file 
    NSURL *filePath = [NSURL fileURLWithPath:path isDirectory:NO]; 
    AudioServicesCreateSystemSoundID((CFURLRef)filePath, &soundID); 
    //play the file 
    AudioServicesPlaySystemSound(soundID); 
} 

回答

10

documentation

讨论本功能起着短 声音(30秒或在持续时间 更小)。因为声音可能在几秒钟内播放 ,所以此功能是 异步执行。要知道何时 声音播放完毕,请拨打 AudioServicesAddSystemSoundCompletion 函数注册回调函数 。

所以你需要你的函数分解成两个部分:调用PlayASound和打印“Hello”的功能,以及一个功能,就是called by the system当声音播放完毕并打印“世界”。

// Change PlayASound to return the SystemSoundID it created 
-(SystemSoundID) playASound: (NSString *) file { 

    //Get the filename of the sound file: 
    NSString *path = [NSString stringWithFormat:@"%@/%@", 
         [[NSBundle mainBundle] resourcePath], 
         file]; 

    SystemSoundID soundID; 
    //Get a URL for the sound file 
    NSURL *filePath = [NSURL fileURLWithPath:path isDirectory:NO]; 
    AudioServicesCreateSystemSoundID((CFURLRef)filePath, &soundID); 
    //play the file 
    AudioServicesPlaySystemSound(soundID); 
    return soundID; 
} 

-(void)startSound 
{ 
    printf("Hello"); 
    SystemSoundID id = [self playASound:@"file.wav"]; 
    AudioServicesAddSystemSoundCompletion (
     id, 
     NULL, 
     NULL, 
     endSound, 
     NULL 
    ); 
} 

void endSound (
    SystemSoundID ssID, 
    void   *clientData 
) 
{ 
    printf("world\n"); 
} 

另请参阅docs for AudioServicesAddSystemSoundCompletionAudioServicesSystemSoundCompletionProc

+0

+1这对我也有帮助 – 2010-08-13 17:23:26

+0

感谢Nicholas – subzero 2010-08-13 17:25:24

+0

“路径”是否会自动释放? – 2012-08-15 14:06:45