iOS SDK

Updated at:

Use the iOS NUI SDK to synthesize speech from text and receive audio data through callbacks. This topic describes SDK integration, the call sequence, code examples, key interfaces, and troubleshooting.

Prerequisites

  • Activate Intelligent Speech Interaction and obtain a project Appkey. For project configuration, see Manage projects.

  • Obtain an NLS token. For instructions, see Obtain an access token.

Important

Keep the AccessKey ID and AccessKey secret on the server. Do not include them in app code or store them on a mobile device. Cloud-based speech synthesis uses an Appkey and an NLS token for authentication. Obtain the token on the server, send it to the app, and update it before it expires.

For synthesis parameters and supported voices, see Text-to-speech API reference for mobile clients.

Download and integrate the SDK

Download an iOS NUI SDK package that supports speech synthesis from Select and download a mobile SDK.

The integration instructions and examples below use the V2.7.4-01B-20260904_iOS_TLS package. iOS interfaces in versions later than 2.5.14 use Objective-C and no longer require mixed C++ interface calls.

  1. Extract the SDK package and select a library for the target platform.

    Library

    Purpose

    Release/nuisdk.xcframework

    Contains iOS arm64 and iOS Simulator arm64 variants for physical devices and simulators on Apple Silicon Macs.

    Release/nuisdk.framework

    Contains arm64 for physical devices and x86_64 for simulators on Intel Macs. Remove simulator architectures before distributing the app for physical devices.

    Release-iphoneos/nuisdk.xcframework

    Contains only arm64 for physical devices.

  2. Add the selected Framework or XCFramework to the Xcode project. Add the library under the target's Build Phases > Link Binary With Libraries, then select Embed & Sign under General > Frameworks, Libraries, and Embedded Content.

  3. Import the speech synthesis header:

        #import <nuisdk/NeoNuiTts.h>

The demo project in the SDK package provides utilities for audio playback and file operations. The speech synthesis example is in TTSViewController, and the player is AudioController. Replace the Appkey and token to run the example. The current cloud-only synthesis mode does not require a workspace resource directory.

Call sequence

  1. Create SDK and player instances, set their delegates, and initialize the SDK.

  2. Call nui_tts_set_param to set the voice, audio format, sample rate, and other parameters.

  3. Call nui_tts_play to start synthesis.

  4. Receive audio data in onNuiTtsUserdataCallback. Write it to the player for streaming playback, or append successive chunks to the same file.

  5. After TTS_EVENT_END, wait for the player to finish playing the buffered audio. This event indicates the end of synthesis, not playback.

  6. Call nui_tts_release when the SDK is no longer needed.

Code examples

The following example uses AudioController.h, AudioController.m, and their dependencies NLSRingBuffer.h and NLSRingBuffer.mm from the demo. Playback uses 16 kHz, 16-bit, mono PCM. Add these utility classes to the project and link AudioToolbox.framework, AVFoundation.framework, and libc++.tbd.

Use [NeoNuiTts get_instance] to obtain the default singleton, or [[NeoNuiTts alloc] init] to create an instance. Initialization may block, so run it off the UI thread. Call control methods sequentially on the same instance. We recommend running only one synthesis task at a time on each instance.

Configure the gateway

NSString *gateway = @"wss://nls-gateway.cn-shanghai.aliyuncs.com/ws/v1";

Initialize, synthesize, and play audio

#import <Foundation/Foundation.h>
#import <nuisdk/NeoNuiTts.h>
#import "AudioController.h"

@interface SpeechSynthesizer : NSObject <NeoNuiTtsDelegate, ConvVoiceRecorderDelegate>
@property(nonatomic, strong) NeoNuiTts *nui;
@property(nonatomic, strong) AudioController *player;
@property(atomic) BOOL finished;
@property(nonatomic, copy) void (^onFinished)(void);
- (int)configureWithAppkey:(NSString *)appkey token:(NSString *)token
                  gateway:(NSString *)gateway;
- (int)startWithText:(NSString *)text;
- (int)cancel;
- (int)releaseSdk;
@end

@implementation SpeechSynthesizer
- (int)configureWithAppkey:(NSString *)appkey token:(NSString *)token
                  gateway:(NSString *)gateway {
    self.finished = YES;
    self.nui = [[NeoNuiTts alloc] init];
    self.nui.delegate = self;
    self.player = [[AudioController alloc] init:only_player];
    self.player.delegate = self;
    [self.player setPlayerSampleRate:16000];

    NSDictionary *params = @{
        @"app_key": appkey,
        @"token": token,
        @"url": gateway,
        @"mode_type": @"2",
        @"device_id": [[NSUUID UUID] UUIDString]
    };
    NSData *data = [NSJSONSerialization dataWithJSONObject:params options:0 error:nil];
    NSString *json = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    int code = [self.nui nui_tts_initialize:json.UTF8String
                                  logLevel:NUI_LOG_LEVEL_NONE saveLog:NO];
    if (code != 0) return code;
    code = [self.nui nui_tts_set_param:"font_name" value:"xiaoyun"];
    if (code != 0) return code;
    code = [self.nui nui_tts_set_param:"encode_type" value:"pcm"];
    if (code != 0) return code;
    return [self.nui nui_tts_set_param:"sample_rate" value:"16000"];
}

- (int)startWithText:(NSString *)text {
    self.finished = NO;
    int code = [self.nui nui_tts_play:"1" taskId:"" text:text.UTF8String];
    if (code != 0) self.finished = YES;
    return code;
}

- (int)cancel {
    return [self.nui nui_tts_cancel:NULL];
}

- (int)releaseSdk {
    [self.player stopPlayer];
    int code = [self.nui nui_tts_release];
    self.nui.delegate = nil;
    self.player.delegate = nil;
    return code;
}

- (void)notifyFinished {
    @synchronized(self) {
        if (self.finished) return;
        self.finished = YES;
    }
    if (self.onFinished) self.onFinished();
}

- (void)onNuiTtsEventCallback:(NuiSdkTtsEvent)event taskId:(char *)taskid code:(int)code {
    if (event == TTS_EVENT_START) {
        [self.player startPlayer];
    } else if (event == TTS_EVENT_END) {
        [self.player drain];
    } else if (event == TTS_EVENT_CANCEL || event == TTS_EVENT_ERROR) {
        [self.player stopPlayer];
        if (event == TTS_EVENT_ERROR) {
            const char *message = [self.nui nui_tts_get_param:"error_msg"];
            NSLog(@"TTS error: %d, %s", code, message ?: "");
        }
        [self notifyFinished];
    }
}

- (void)onNuiTtsUserdataCallback:(char *)info infoLen:(int)infoLength
                        buffer:(char *)buffer len:(int)length taskId:(char *)taskid {
    if (length > 0) [self.player write:buffer Length:length];
}

- (void)playerDrainDataFinish {
    [self notifyFinished];
}
- (void)playerDidStart {}
- (void)playerDidFinish {}
- (void)playSoundLevel:(int)level {}
- (void)playData:(unsigned char *)buffer Length:(int)length {}
- (void)recorderDidStart {}
- (void)recorderDidStop {}
- (void)voiceRecorded:(unsigned char *)buffer Length:(int)length {}
- (void)voiceDidFail:(NSError *)error {}
@end

Keep a SpeechSynthesizer instance in the business object and use a serial queue for control calls. Replace appkey and token with the values supplied by the server. Use the gateway configured above.

// Declare these properties in the business object.
@property(nonatomic, strong) SpeechSynthesizer *synthesizer;
@property(nonatomic, strong) dispatch_queue_t ttsQueue;

// Start synthesis in a business method.
self.ttsQueue = dispatch_queue_create("tts.control", DISPATCH_QUEUE_SERIAL);
self.synthesizer = [SpeechSynthesizer new];
SpeechSynthesizer *synthesizer = self.synthesizer;
dispatch_queue_t queue = self.ttsQueue;
__weak typeof(self) weakSelf = self;
synthesizer.onFinished = ^{
    dispatch_async(queue, ^{
        int code = [synthesizer releaseSdk];
        if (code != 0) NSLog(@"Release failed: %d", code);
        synthesizer.onFinished = nil;
        dispatch_async(dispatch_get_main_queue(), ^{
            weakSelf.synthesizer = nil;
        });
    });
};
dispatch_async(queue, ^{
    int code = [synthesizer configureWithAppkey:appkey token:token gateway:gateway];
    if (code == 0) code = [synthesizer startWithText:@"Hello, welcome to the speech synthesis example."];
    if (code != 0) {
        NSLog(@"Start failed: %d", code);
        [synthesizer releaseSdk];
        synthesizer.onFinished = nil;
        dispatch_async(dispatch_get_main_queue(), ^{
            weakSelf.synthesizer = nil;
        });
    }
});

To cancel before completion, call cancel on the same serial queue. It passes NULL to cancel all synthesis tasks on the instance. Schedule resource release asynchronously on the control queue, rather than directly in an SDK event callback.

Key interfaces and callbacks

Except for nui_tts_get_param, which returns a parameter value, the following methods return integer status codes. A value of 0 indicates a successful call. Asynchronous synthesis errors are reported through TTS_EVENT_ERROR.

For error codes and solutions, see Error code reference.

Control methods

Initialization and configuration

nui_tts_initialize: Initializes the SDK. Release SDK resources on an instance before initializing it again. This call may block and must run off the UI thread.

- (int)nui_tts_initialize:(const char *)parameters
                 logLevel:(NuiSdkLogLevel)level
                  saveLog:(BOOL)save_log;
  • parameters: A JSON string containing initialization parameters such as app_key, token, url, mode_type, and device_id. For cloud-only synthesis, mode_type must be "2", and the required device_id must be set. We recommend a unique device identifier to help locate issues.

  • level: The log level. Lower enum values produce more detailed logs. Examples include NUI_LOG_LEVEL_VERBOSE and NUI_LOG_LEVEL_NONE.

  • save_log: Whether to save logs to files. When enabled, set the directory with the initialization parameter debug_path and monitor log storage usage. The current demo supports max_log_file_size to configure log file size.

nui_tts_set_param: Sets synthesis parameters as key-value pairs.

- (int)nui_tts_set_param:(const char *)param value:(const char *)value;

param is the parameter name, and value is its value. Configurable synthesis parameters include voice, pitch, and speech rate. For example, font_name selects the voice, and encode_type sets the audio format.

Synthesis task control

nui_tts_play: Starts synthesis. Audio is delivered to the app through the data callback for playback or storage.

- (int)nui_tts_play:(const char *)priority
             taskId:(const char *)taskid
              text:(const char *)text;
  • priority: The task priority. Use "1".

  • taskid: The task ID. Pass a 32-byte UUID or an empty string to let the SDK generate an ID.

  • text: The text to synthesize.

nui_tts_cancel: Cancels synthesis. taskid specifies the task to cancel. Pass NULL to cancel all tasks.

- (int)nui_tts_cancel:(const char *)taskid;

nui_tts_pause / nui_tts_resume: Pauses or resumes a synthesis task. The app's player controls audio that is already buffered.

- (int)nui_tts_pause;
- (int)nui_tts_resume;

Parameter queries and resource release

nui_tts_get_param: Queries a parameter. param specifies the name, and the return value is the parameter value. For example, query error_msg to obtain error details.

- (const char *)nui_tts_get_param:(const char *)param;

nui_tts_release: Releases SDK resources.

- (int)nui_tts_release;

Audio data callback

The onNuiTtsUserdataCallback method in NeoNuiTtsDelegate delivers synthesized audio and available timestamp information to the app.

- (void)onNuiTtsUserdataCallback:(char *)info infoLen:(int)info_len
                        buffer:(char *)buffer len:(int)len taskId:(char *)task_id;
  • info: Timestamp information in JSON format, when timestamps are enabled and the voice supports them.

  • info_len: The length of info.

  • buffer: Synthesized audio data.

  • len: The length of the audio data, in bytes.

  • task_id: The ID of the current synthesis task.

Event callback

onNuiTtsEventCallback reports the synthesis state. The app can use these events to control the player.

- (void)onNuiTtsEventCallback:(NuiSdkTtsEvent)event taskId:(char *)taskid code:(int)code;

event is the event type, and taskid is the ID of the current synthesis task. code is an error code and is valid only for TTS_EVENT_ERROR.

Event

Description

TTS_EVENT_START

Synthesis starts. Prepare for playback.

TTS_EVENT_END

Synthesis ends. All audio has been delivered through callbacks, but the player may still have buffered audio to play.

TTS_EVENT_CANCEL

The synthesis task is canceled.

TTS_EVENT_PAUSE

The synthesis task is paused.

TTS_EVENT_RESUME

The synthesis task is resumed.

TTS_EVENT_ERROR

An error occurs during synthesis.

FAQ

How do I resolve noise when playing saved audio?

Check whether the actual encoding matches a format supported by the player. For example, use a player that supports MP3 to play MP3 data. If noise occurs at the end of the audio, check whether log text or other non-audio data was written to the file.

What can I do if frequent playback requests cause the app page to terminate?

Cloud-based synthesis requires a network connection, and network conditions affect response time. If the app needs to stop a task and quickly start the next one, you can adjust the network timeout based on network conditions and business requirements.

How do I save synthesized audio to a file?

Set encode_type with nui_tts_set_param to select PCM, WAV, or MP3. In onNuiTtsUserdataCallback, append successive audio chunks to the same file in order. Close the file after TTS_EVENT_END.

The example player on this page plays PCM streams. Use software that supports MP3 to play saved MP3 files. If the saved audio is missing words, check whether every callback's data was written completely, especially when audio is generated quickly. When saving with fwrite, you can call fflush after writing to flush the file buffer. Call fclose after synthesis ends.

How do I obtain timestamps?

Timestamps are not returned by default. Select a voice that supports timestamps and call nui_tts_set_param:"enable_subtitle" value:"1" before starting synthesis. Then obtain the result from info in onNuiTtsUserdataCallback.

For parameter details, see Text-to-speech API reference for mobile clients.

Can mobile SDKs be used in a private cloud?

Mobile SDKs can call ASR and TTS services in the public cloud and can also be used in a private cloud. Private cloud installation packages do not include mobile SDKs by default. Download them from the corresponding service topics in the help center, such as the Android SDK and iOS SDK for real-time speech recognition.

Is background playback supported?

The SDK itself does not restrict foreground or background operation. The app must configure iOS background audio capability. In Info.plist, add Required background modes and App plays audio or streams audio/video using AirPlay, which sets UIBackgroundModes to include audio. The player must also configure and activate an audio session.

How do I resolve no suitable image found on a physical device?

Verify that the integrated library contains an iOS device architecture, then check Embed & Sign and app signing settings. After fixing the configuration, clean the build products, remove the old app from the device, and reinstall it.

How do I resolve a speech synthesis header import failure?

Verify that the SDK is added under Link Binary With Libraries and set to Embed & Sign. For speech synthesis, use #import <nuisdk/NeoNuiTts.h>. If using the demo player, also add its utility classes and library dependencies.

What if an older Framework reports that it contains both iOS and iOS Simulator platforms?

Prefer an XCFramework variant that matches the target platform. When integrating a mixed-platform Framework with an older Xcode version, select All > Combined in Build Settings, then set Build Options > Validate Workspace to Yes and rebuild.

An older project runs only after switching to Legacy Build System

For this build issue in an older Xcode project, check Validate Workspace, set it to Yes, and rebuild.

How do I resolve undefined std::__1::mutex symbols in a Flutter project?

Add libc++.tbd under the iOS target's Build Phases > Link Binary With Libraries to link the C++ runtime. If the error involves a plugin library, also check the plugin target's linker configuration.

How do I resolve Unsupported Architectures during App Store submission?

A distribution package for physical devices must not contain simulator architectures. For an XCFramework, select the iOS device variant. For an older mixed Framework, inspect the binary with lipo -info nuisdk.framework/nuisdk. Remove simulator architectures, then sign and package it again.