播放声音,等待它完成播放并继续(iphone)

时间:2010-08-13 16:56:32

标签: iphone objective-c iphone-sdk-3.0

我是iphone和Objective c的新手,到目前为止,我已经能够编写一些小例子了。

我想播放声音,并在示例播放完毕后继续使用其余代码,即:

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

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

感谢

顺便说一句。这是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);
}

1 个答案:

答案 0 :(得分:10)

来自documentation

  

讨论此功能很简短   声音(30秒或更短时间)   持续时间)。因为声音可能会播放   几秒钟,这个功能是   异步执行。知道什么时候   声音播放完毕,打电话给   AudioServicesAddSystemSoundCompletion   用于注册回调的函数   功能

所以你需要把你的功能分成两部分:一个调用PlayASound并打印“Hello”的函数,以及一个声音播放完毕后打印“World”的函数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