我试图用C的CoreFoundation接口,语音合成管理器。 你如何注册一个回调的讲话(如kSpeechSpeechDoneCallBack
或kSpeechTextDoneCallBack
)? 我知道如何使用旧的过时SetSpeechInfo
功能; 你怎么跟新做SetSpeechProperty
? 当我尝试使用它,它会导致“段错误:11”,而不是叫我注册的功能。
根据语音通道属性 ,我认为你应该在通过long
CFNumberRef
其值是所需的函数指针。
这里就是主线程注册一个回调并等待语音完成一个简单的例子。 而是调用回调,调度线程提供了错误“EXC_BAD_ACCESS(代码= 13,地址=为0x0)”。 使用过时的功能( --old
),回调被调用时不会出错。
// clang -g -framework ApplicationServices main.c && ./a.out
#include <stdio.h>
#include <pthread.h>
#include <ApplicationServices/ApplicationServices.h>
void checkResult(OSErr error, const char *description) {
if (error == 0)
return;
fprintf(stderr, "Error: %d during %s. exiting.", error, description);
exit(error);
}
struct SpeechState {
pthread_mutex_t mutex;
pthread_cond_t speakingDone;
int stillSpeakingCount;
};
void speechDone(SpeechChannel chan, SRefCon refCon) {
printf("Speech done!\n");
struct SpeechState *speechState = (struct SpeechState*)refCon;
pthread_mutex_lock(&speechState->mutex);
speechState->stillSpeakingCount--;
pthread_cond_broadcast(&speechState->speakingDone);
pthread_mutex_unlock(&speechState->mutex);
}
int main(int argc, const char * argv[])
{
bool old = false;
for (int i = 1; i < argc; i++) {
if (0 == strcmp(argv[i], "--old"))
old = true;
}
SpeechChannel chan;
checkResult(NewSpeechChannel((VoiceSpec*)NULL, &chan), "NewSpeechChannel");
struct SpeechState speechState;
pthread_mutex_init(&speechState.mutex, NULL);
pthread_cond_init(&speechState.speakingDone, NULL);
if (! old) {
// The new way seems to crash.
CFNumberRef doneCallbackNumber = CFNumberCreate(NULL, kCFNumberLongType, speechDone);
CFNumberRef refConNumber = CFNumberCreate(NULL, kCFNumberLongType, &speechState);
printf("Registering speechDone callback for address %p\n", speechDone);
checkResult(SetSpeechProperty(chan, kSpeechSpeechDoneCallBack, doneCallbackNumber), "SetSpeechProperty(sdcb)");
checkResult(SetSpeechProperty(chan, kSpeechRefConProperty, refConNumber), "SetSpeechProperty(refc)");
CFRelease(doneCallbackNumber);
CFRelease(refConNumber);
} else {
// The deprecated way to do it works.
checkResult(SetSpeechInfo(chan, soSpeechDoneCallBack, &speechDone), "SetSpeechInfo(sdcb)");
checkResult(SetSpeechInfo(chan, soRefCon, &speechState), "SetSpeechInfo(refc)");
}
printf("Speaking...\n");
CFStringRef string = CFStringCreateWithCString(NULL, "Most people recognize me by my voice!", kCFStringEncodingUTF8);
checkResult(SpeakCFString(chan, string, NULL), "SpeakCFString");
CFRelease(string);
pthread_mutex_lock(&speechState.mutex);
speechState.stillSpeakingCount++;
while (speechState.stillSpeakingCount > 0) {
pthread_cond_wait(&speechState.speakingDone, &speechState.mutex);
}
pthread_mutex_unlock(&speechState.mutex);
printf("Done!\n");
return 0;
}