Swift Examples - ElevenLabs

Step 1

Add the AIProxySwift package to your Xcode project

  1. Open your Xcode project
  2. Select File > Add Package Dependencies
  3. Paste github.com/lzell/aiproxyswift into the package URL bar
  4. Click Add Package
Step 2

Initialize

Import AIProxy and initialize using the following code:

import AIProxy

let elevenLabsService = AIProxy.elevenLabsService(
    partialKey: "partial-key-from-your-developer-dashboard",
    serviceURL: "service-url-from-your-developer-dashboard"
)
Step 3

Setup DeviceCheck

Before adding the DeviceCheck ENV variable check these three things: 1) in Xcode check that your Apple developer team is selected under the 'Signing & Capabilities' tab 2) make sure the bundle ID of your app is explicit (i.e. it can't contain a wildcard) 3) make sure the bundle ID in Xcode matches a bundle ID listed on the Identifers page in the Apple Developer dashboard.

Add the AIPROXY_DEVICE_CHECK_BYPASS env variable to your Xcode project:

  • Type cmd-shift-comma to open up the "Edit Schemes" menu
  • Select Run in the sidebar
  • Add to the "Environment Variables" section (not the "Arguments Passed on Launch" section) an env variable with name AIPROXY_DEVICE_CHECK_BYPASS and value that we provided you in the AIProxy dashboard.

How to use ElevenLabs for text-to-speech

import AIProxy

let elevenLabsService = AIProxy.elevenLabsService(
    partialKey: "partial-key-from-your-developer-dashboard",
    serviceURL: "service-url-from-your-developer-dashboard"
)
do {
    let body = ElevenLabsTTSRequestBody(
        text: "Hello world"
    )
    let mpegData = try await elevenLabsService.ttsRequest(
        voiceID: "EXAVITQu4vr4xnSDxMaL",
        body: body
    )

    // Do not use a local `let` or `var` for AVAudioPlayer.
    // You need the lifecycle of the player to live beyond the scope of this function.
    // Instead, use file scope or set the player as a member of a reference type with long life.
    // For example, at the top of this file you may define:
    //
    //   fileprivate var audioPlayer: AVAudioPlayer? = nil
    //
    // And then use the code below to play the TTS result:
    audioPlayer = try AVAudioPlayer(data: mpegData)
    audioPlayer?.prepareToPlay()
    audioPlayer?.play()
}  catch AIProxyError.unsuccessfulRequest(let statusCode, let responseBody) {
    print("Received \(statusCode) status code with response body: \(responseBody)")
} catch {
    print("Could not create ElevenLabs TTS audio: \(error.localizedDescription)")
}