gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 20:21:21 29 4
gpt4 key购买 nike

我是 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);
}

最佳答案

来自documentation :

Discussion This function plays a short sound (30 seconds or less in duration). Because sound might play for several seconds, this function is executed asynchronously. To know when a sound has finished playing, call the AudioServicesAddSystemSoundCompletion function to register a callback function.

因此,您需要将函数分成两部分:一个调用 PlayASound 并打印“Hello”的函数,以及一个 called by the system 的函数。当声音播放完毕并打印“World”时。

// 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 .

关于iphone - 播放声音,等待播放完成并继续 (iphone),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3479075/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com