Giter Club home page Giter Club logo

espeakng-sys's Introduction

eSpeak NG bindings for Rust

Crates.io
FFI bindings to the C library eSpeak NG for Rust

Current eSpeak NG version: 1.51

Dependencies

Example

This example shows how you can convert a &str to a Vec

#![allow(non_upper_case_globals)]

use espeakng_sys::*;
use std::os::raw::{c_char, c_short, c_int};
use std::ffi::{c_void, CString};
use std::cell::Cell;
use lazy_static::lazy_static;
use std::sync::{Mutex, MutexGuard};

/// The name of the voice to use
const VOICE_NAME: &str = "English";
/// The length in mS of sound buffers passed to the SynthCallback function.
const BUFF_LEN: i32 = 500;
/// Options to set for espeak-ng
const OPTIONS: i32 = 0;

lazy_static! {
    /// The complete audio provided by the callback
    static ref AUDIO_RETURN: Mutex<Cell<Vec<i16>>> = Mutex::new(Cell::new(Vec::default()));

    /// Audio buffer for use in the callback
    static ref AUDIO_BUFFER: Mutex<Cell<Vec<i16>>> = Mutex::new(Cell::new(Vec::default()));
}

/// Spoken speech
pub struct Spoken {
    /// The audio data
    pub wav:            Vec<i16>,
    /// The sample rate of the audio
    pub sample_rate:    i32
}

/// Perform Text-To-Speech
pub fn speak(text: &str) -> Spoken {
    let output: espeak_AUDIO_OUTPUT = espeak_AUDIO_OUTPUT_AUDIO_OUTPUT_RETRIEVAL;

    AUDIO_RETURN.plock().set(Vec::default());
    AUDIO_BUFFER.plock().set(Vec::default());

    // The directory which contains the espeak-ng-data directory, or NULL for the default location.
    let path: *const c_char = std::ptr::null();
    let voice_name_cstr = CString::new(VOICE_NAME).expect("Failed to convert &str to CString");
    let voice_name = voice_name_cstr.as_ptr();

    // Returns: sample rate in Hz, or -1 (EE_INTERNAL_ERROR).
    let sample_rate = unsafe { espeak_Initialize(output, BUFF_LEN, path, OPTIONS) };

    unsafe {
        espeak_SetVoiceByName(voice_name as *const c_char);
        espeak_SetSynthCallback(Some(synth_callback))
    }

    let text_cstr = CString::new(text).expect("Failed to convert &str to CString");

    let position = 0u32;
    let position_type: espeak_POSITION_TYPE = 0;
    let end_position = 0u32;
    let flags = espeakCHARS_AUTO;
    let identifier = std::ptr::null_mut();
    let user_data = std::ptr::null_mut();

    unsafe { espeak_Synth(text_cstr.as_ptr() as *const c_void, BUFF_LEN as size_t, position, position_type, end_position, flags, identifier, user_data); }

    // Wait for the speaking to complete
    match unsafe { espeak_Synchronize() } {
        espeak_ERROR_EE_OK => {},
        espeak_ERROR_EE_INTERNAL_ERROR => {
            todo!()
        }
        _ => unreachable!()
    }

    let result = AUDIO_RETURN.plock().take();

    Spoken {
        wav: result,
        sample_rate
    }
}

/// int SynthCallback(short *wav, int numsamples, espeak_EVENT *events);
///
/// wav:  is the speech sound data which has been produced.
/// NULL indicates that the synthesis has been completed.
///
/// numsamples: is the number of entries in wav.  This number may vary, may be less than
/// the value implied by the buflength parameter given in espeak_Initialize, and may
/// sometimes be zero (which does NOT indicate end of synthesis).
///
/// events: an array of espeak_EVENT items which indicate word and sentence events, and
/// also the occurance if <mark> and <audio> elements within the text.  The list of
/// events is terminated by an event of type = 0.
///
/// Callback returns: 0=continue synthesis,  1=abort synthesis.
unsafe extern "C" fn synth_callback(wav: *mut c_short, sample_count: c_int, events: *mut espeak_EVENT) -> c_int {

    // Calculate the length of the events array
    let mut events_copy = events.clone();
    let mut elem_count = 0;
    while (*events_copy).type_ != espeak_EVENT_TYPE_espeakEVENT_LIST_TERMINATED {
        elem_count += 1;
        events_copy = events_copy.add(1);
    }

    // Turn the event array into a Vec.
    // We must clone from the slice, as the provided array's memory is managed by C
    let event_slice = std::slice::from_raw_parts_mut(events, elem_count);
    let event_vec = event_slice.into_iter()
        .map(|f| f.clone())
        .collect::<Vec<espeak_EVENT>>();

    // Turn the audio wav data array into a Vec.
    // We must clone from the slice, as the provided array's memory is managed by C
    let wav_slice = std::slice::from_raw_parts_mut(wav, sample_count as usize);
    let mut wav_vec = wav_slice.into_iter()
        .map(|f| f.clone() as i16)
        .collect::<Vec<i16>>();

    // Determine if this is the end of the synth
    let mut is_end = false;
    for event in event_vec {
        if event.type_.eq(&espeak_EVENT_TYPE_espeakEVENT_MSG_TERMINATED) {
            is_end = true;
        }
    }

    // If this is the end, we want to set the AUDIO_RETURN
    // Else we want to append to the AUDIO_BUFFER
    if is_end {
        AUDIO_RETURN.plock().set(AUDIO_BUFFER.plock().take());
    } else {
        let mut curr_data = AUDIO_BUFFER.plock().take();
        curr_data.append(&mut wav_vec);
        AUDIO_BUFFER.plock().set(curr_data);
    }

    0
}

trait PoisonlessLock<T> {
    fn plock(&self) -> MutexGuard<T>;
}

impl<T> PoisonlessLock<T> for Mutex<T> {
    fn plock(&self) -> MutexGuard<T> {
        match self.lock() {
            Ok(l) => l,
            Err(e) => e.into_inner()
        }
    }

Common issues

  1. 'a `libclang` shared library is not loaded on this thread'

    Enable the clang-runtime feature.

  2. (Flatpack) /usr/lib/sdk/llvm16/lib/libclang.so: undefined reference to `LLVMInitializeWebAssemblyAsmPrinter@LLVM_16'

    Enable the clang-runtime feature.

License

espeakng-sys is dual licensed under the Apache-2.0 and MIT license, at your discretion. Do note though, espeak-ng itself is licensed under the GPL

espeakng-sys's People

Contributors

tobiasdebruijn avatar jesse-bakker avatar eeejay avatar gnomeddev avatar themuso avatar

Stargazers

VirtualPierogi avatar  avatar Andrew Grathwohl avatar  avatar Hendrik avatar コマリン親衛隊 avatar Andrew Gazelka avatar Liam Dyer avatar  avatar Mitchell Tannenbaum avatar

Watchers

 avatar

espeakng-sys's Issues

Release 0.1.3 was a breaking change.

According to cargo's version of semver, 0.X.Y where Y is incremented should be non-breaking, however it seems that espeak_ng_Synthesize's second argument changed from u64 to usize. The best solution going forward would be to yank 0.1.3 to prevent cargo automatically breaking projects which depend on this library when a cargo update is run, then re-release it as 0.2.

Installing in Flatpak

I'm trying to use this in flatpak but it fails to compile with:

error: linking with `cc` failed: exit status: 1
  |
  = note: LC_ALL="C" PATH="/usr/lib/sdk/rust-stable/lib/rustlib/x86_64-unknown-linux-gnu/bin:/app/bin:/usr/bin:/usr/lib/sdk/rust-stable/bin" VSLANG="1033" "cc" "-m64" "/tmp/rustcmhQ4Bt/symbols.o" "/home/dan/.cache/gnome-builder/projects/jogger/builds/xyz.slothlife.Jogger.json-flatpak-org.gnome.Platform-45beta-x86_64-espeak-ng/src/debug/build/espeakng-sys-a92592724e610fed/build_script_build-a92592724e610fed.build_script_build.748b7017790f522e-cgu.0.rcgu.o" "/home/dan/.cache/gnome-builder/projects/jogger/builds/xyz.slothlife.Jogger.json-flatpak-org.gnome.Platform-45beta-x86_64-espeak-ng/src/debug/build/espeakng-sys-a92592724e610fed/build_script_build-a92592724e610fed.49vsipmlusyfzxae.rcgu.o" "-Wl,--as-needed" "-L" "/home/dan/.cache/gnome-builder/projects/jogger/builds/xyz.slothlife.Jogger.json-flatpak-org.gnome.Platform-45beta-x86_64-espeak-ng/src/debug/deps" "-L" "/usr/lib/sdk/llvm16/lib" "-L" "/usr/lib/sdk/rust-stable/lib/rustlib/x86_64-unknown-linux-gnu/lib" "-Wl,-Bstatic" "/home/dan/.cache/gnome-builder/projects/jogger/builds/xyz.slothlife.Jogger.json-flatpak-org.gnome.Platform-45beta-x86_64-espeak-ng/src/debug/deps/libbindgen-ac27aca53e58e6e7.rlib" "/home/dan/.cache/gnome-builder/projects/jogger/builds/xyz.slothlife.Jogger.json-flatpak-org.gnome.Platform-45beta-x86_64-espeak-ng/src/debug/deps/libshlex-b2a8a911f5980326.rlib" "/home/dan/.cache/gnome-builder/projects/jogger/builds/xyz.slothlife.Jogger.json-flatpak-org.gnome.Platform-45beta-x86_64-espeak-ng/src/debug/deps/librustc_hash-7b05e4fe75b58264.rlib" "/home/dan/.cache/gnome-builder/projects/jogger/builds/xyz.slothlife.Jogger.json-flatpak-org.gnome.Platform-45beta-x86_64-espeak-ng/src/debug/deps/libregex-83aa7728f1ed84b5.rlib" "/home/dan/.cache/gnome-builder/projects/jogger/builds/xyz.slothlife.Jogger.json-flatpak-org.gnome.Platform-45beta-x86_64-espeak-ng/src/debug/deps/libregex_automata-eb447f951ca62371.rlib" "/home/dan/.cache/gnome-builder/projects/jogger/builds/xyz.slothlife.Jogger.json-flatpak-org.gnome.Platform-45beta-x86_64-espeak-ng/src/debug/deps/libaho_corasick-5758ce179aee613c.rlib" "/home/dan/.cache/gnome-builder/projects/jogger/builds/xyz.slothlife.Jogger.json-flatpak-org.gnome.Platform-45beta-x86_64-espeak-ng/src/debug/deps/libregex_syntax-acc9cef604855d12.rlib" "/home/dan/.cache/gnome-builder/projects/jogger/builds/xyz.slothlife.Jogger.json-flatpak-org.gnome.Platform-45beta-x86_64-espeak-ng/src/debug/deps/liblazycell-2c5b1cc05b5e4507.rlib" "/home/dan/.cache/gnome-builder/projects/jogger/builds/xyz.slothlife.Jogger.json-flatpak-org.gnome.Platform-45beta-x86_64-espeak-ng/src/debug/deps/libpeeking_take_while-36ee259dee51fb21.rlib" "/home/dan/.cache/gnome-builder/projects/jogger/builds/xyz.slothlife.Jogger.json-flatpak-org.gnome.Platform-45beta-x86_64-espeak-ng/src/debug/deps/libcexpr-7ea9e34a881791fa.rlib" "/home/dan/.cache/gnome-builder/projects/jogger/builds/xyz.slothlife.Jogger.json-flatpak-org.gnome.Platform-45beta-x86_64-espeak-ng/src/debug/deps/libnom-7e6276d44588c7c9.rlib" "/home/dan/.cache/gnome-builder/projects/jogger/builds/xyz.slothlife.Jogger.json-flatpak-org.gnome.Platform-45beta-x86_64-espeak-ng/src/debug/deps/libmemchr-333149cdd616a6c6.rlib" "/home/dan/.cache/gnome-builder/projects/jogger/builds/xyz.slothlife.Jogger.json-flatpak-org.gnome.Platform-45beta-x86_64-espeak-ng/src/debug/deps/libclang_sys-3a5fedfa1ef6c87a.rlib" "/home/dan/.cache/gnome-builder/projects/jogger/builds/xyz.slothlife.Jogger.json-flatpak-org.gnome.Platform-45beta-x86_64-espeak-ng/src/debug/deps/liblibc-073486283dd4d0b5.rlib" "/home/dan/.cache/gnome-builder/projects/jogger/builds/xyz.slothlife.Jogger.json-flatpak-org.gnome.Platform-45beta-x86_64-espeak-ng/src/debug/deps/libglob-f70ac4a9ca01fc44.rlib" "/home/dan/.cache/gnome-builder/projects/jogger/builds/xyz.slothlife.Jogger.json-flatpak-org.gnome.Platform-45beta-x86_64-espeak-ng/src/debug/deps/libquote-bf307f1af43a2537.rlib" "/home/dan/.cache/gnome-builder/projects/jogger/builds/xyz.slothlife.Jogger.json-flatpak-org.gnome.Platform-45beta-x86_64-espeak-ng/src/debug/deps/libproc_macro2-239f331b1f056075.rlib" "/home/dan/.cache/gnome-builder/projects/jogger/builds/xyz.slothlife.Jogger.json-flatpak-org.gnome.Platform-45beta-x86_64-espeak-ng/src/debug/deps/libunicode_ident-d135402c5721d012.rlib" "/usr/lib/sdk/rust-stable/lib/rustlib/x86_64-unknown-linux-gnu/lib/libproc_macro-475723c0bac0f80c.rlib" "/home/dan/.cache/gnome-builder/projects/jogger/builds/xyz.slothlife.Jogger.json-flatpak-org.gnome.Platform-45beta-x86_64-espeak-ng/src/debug/deps/liblazy_static-643a017f62beb017.rlib" "/home/dan/.cache/gnome-builder/projects/jogger/builds/xyz.slothlife.Jogger.json-flatpak-org.gnome.Platform-45beta-x86_64-espeak-ng/src/debug/deps/libbitflags-1926cec1a16924e0.rlib" "/usr/lib/sdk/rust-stable/lib/rustlib/x86_64-unknown-linux-gnu/lib/libstd-8f88c761e33f2651.rlib" "/usr/lib/sdk/rust-stable/lib/rustlib/x86_64-unknown-linux-gnu/lib/libpanic_unwind-f9018f9cee1cc5ff.rlib" "/usr/lib/sdk/rust-stable/lib/rustlib/x86_64-unknown-linux-gnu/lib/libobject-919f89587cbed68d.rlib" "/usr/lib/sdk/rust-stable/lib/rustlib/x86_64-unknown-linux-gnu/lib/libmemchr-c6624cb4360306cd.rlib" "/usr/lib/sdk/rust-stable/lib/rustlib/x86_64-unknown-linux-gnu/lib/libaddr2line-4930b3dc482158f7.rlib" "/usr/lib/sdk/rust-stable/lib/rustlib/x86_64-unknown-linux-gnu/lib/libgimli-65bea4bb6af40828.rlib" "/usr/lib/sdk/rust-stable/lib/rustlib/x86_64-unknown-linux-gnu/lib/librustc_demangle-bc6864da821ce9a2.rlib" "/usr/lib/sdk/rust-stable/lib/rustlib/x86_64-unknown-linux-gnu/lib/libstd_detect-1bccb7a942e1b311.rlib" "/usr/lib/sdk/rust-stable/lib/rustlib/x86_64-unknown-linux-gnu/lib/libhashbrown-356231f77d1e268a.rlib" "/usr/lib/sdk/rust-stable/lib/rustlib/x86_64-unknown-linux-gnu/lib/librustc_std_workspace_alloc-80ed5799bf463787.rlib" "/usr/lib/sdk/rust-stable/lib/rustlib/x86_64-unknown-linux-gnu/lib/libminiz_oxide-9c3df673b2797081.rlib" "/usr/lib/sdk/rust-stable/lib/rustlib/x86_64-unknown-linux-gnu/lib/libadler-c6afbee8d1102512.rlib" "/usr/lib/sdk/rust-stable/lib/rustlib/x86_64-unknown-linux-gnu/lib/libunwind-682387162b570769.rlib" "/usr/lib/sdk/rust-stable/lib/rustlib/x86_64-unknown-linux-gnu/lib/libcfg_if-05a2cedbb78c1d4f.rlib" "/usr/lib/sdk/rust-stable/lib/rustlib/x86_64-unknown-linux-gnu/lib/liblibc-f002c8f83a289c4b.rlib" "/usr/lib/sdk/rust-stable/lib/rustlib/x86_64-unknown-linux-gnu/lib/liballoc-649be05783c8912e.rlib" "/usr/lib/sdk/rust-stable/lib/rustlib/x86_64-unknown-linux-gnu/lib/librustc_std_workspace_core-13da980d6c74fec5.rlib" "/usr/lib/sdk/rust-stable/lib/rustlib/x86_64-unknown-linux-gnu/lib/libcore-46a989d0e2cef827.rlib" "/usr/lib/sdk/rust-stable/lib/rustlib/x86_64-unknown-linux-gnu/lib/libcompiler_builtins-b114db70ea0690b1.rlib" "-Wl,-Bdynamic" "-lclang" "-lc" "-lm" "-lrt" "-lpthread" "-lgcc_s" "-lutil" "-lrt" "-lpthread" "-lm" "-ldl" "-lc" "-Wl,--eh-frame-hdr" "-Wl,-z,noexecstack" "-L" "/usr/lib/sdk/rust-stable/lib/rustlib/x86_64-unknown-linux-gnu/lib" "-o" "/home/dan/.cache/gnome-builder/projects/jogger/builds/xyz.slothlife.Jogger.json-flatpak-org.gnome.Platform-45beta-x86_64-espeak-ng/src/debug/build/espeakng-sys-a92592724e610fed/build_script_build-a92592724e610fed" "-Wl,--gc-sections" "-pie" "-Wl,-z,relro,-z,now" "-nodefaultlibs"
  = note: /usr/lib/gcc/x86_64-unknown-linux-gnu/13.2.0/../../../../x86_64-unknown-linux-gnu/bin/ld: /usr/lib/sdk/llvm16/lib/libclang.so: undefined reference to `LLVMInitializeWebAssemblyAsmPrinter@LLVM_16'
          /usr/lib/gcc/x86_64-unknown-linux-gnu/13.2.0/../../../../x86_64-unknown-linux-gnu/bin/ld: /usr/lib/sdk/llvm16/lib/libclang.so: undefined reference to `LLVMInitializeWebAssemblyAsmParser@LLVM_16'
          /usr/lib/gcc/x86_64-unknown-linux-gnu/13.2.0/../../../../x86_64-unknown-linux-gnu/bin/ld: /usr/lib/sdk/llvm16/lib/libclang.so: undefined reference to `LLVMInitializeWebAssemblyTarget@LLVM_16'
          /usr/lib/gcc/x86_64-unknown-linux-gnu/13.2.0/../../../../x86_64-unknown-linux-gnu/bin/ld: /usr/lib/sdk/llvm16/lib/libclang.so: undefined reference to `LLVMInitializeWebAssemblyTargetInfo@LLVM_16'
          /usr/lib/gcc/x86_64-unknown-linux-gnu/13.2.0/../../../../x86_64-unknown-linux-gnu/bin/ld: /usr/lib/sdk/llvm16/lib/libclang.so: undefined reference to `LLVMInitializeWebAssemblyTargetMC@LLVM_16'
          collect2: error: ld returned 1 exit status
          
  = note: some `extern` functions couldn't be found; some native libraries may need to be installed or have their path specified
  = note: use the `-l` flag to specify native libraries to link
  = note: use the `cargo:rustc-link-lib` directive to specify the native libraries to link with Cargo (see https://doc.rust-lang.org/cargo/reference/build-scripts.html#cargorustc-link-libkindname)

error: could not compile `espeakng-sys` (build script) due to previous error
warning: build failed, waiting for other jobs to finish...

espeak-ng is being installed with:

{
            "name": "espeak-ng",
            "buildsystem" : "autotools",
            "no-parallel-make": true,
            "build-options": {
                "ldflags": "-Wl,--allow-multiple-definition"
            },
            "sources": [
                {
                    "type": "git",
                    "url": "https://github.com/espeak-ng/espeak-ng.git",
                    "tag": "1.51",
                    "commit": "2e9a5fccbb0095e87b2769e9249ea1f821918ecd"
                }
            ]
        },

and seems to install successfully.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.