Building a Local E-Book Reader with Text-to-Speech on Mobile: A Technical Implementation Guide

    This article breaks down the technical architecture for reading local e-books and listening to them via text-to-speech on mobile devices. It covers file import and format parsing, layout and rendering performance, the text-to-speech pipeline, background playback with resume support, and engineering pitfalls, along with an acceptance checklist.

    1. Problem Background and Goals

    Handling local e-books on mobile may look like simply “reading a file and displaying it,” but it actually requires coordination across multiple subsystems: file parsing, layout, state persistence, speech synthesis, and background scheduling. The original requirements can be abstracted into three technical goals:

    1. Reliable import of common plain-text and rich-text e-books.
    2. A listening (text-to-speech) capability that runs stably for long periods.
    3. Progress that is not lost when switching tasks, locking the screen, or receiving a call.

    It is important to note that different devices and OS versions have different policies for background audio, file access permissions, and notification-bar control. The design must treat these differences as constraints, not as after-the-fact patches.

    2. File Import and Format Parsing Layer

    The first step in importing a local book is obtaining file access. Modern mobile platforms generally use a restricted file-access model. The recommended approach is to obtain one-time authorization through the system file picker and persist that authorization, rather than requesting overly broad storage permissions. After import, copy the file into the app’s private directory and build an index, so the content does not become invalid if the user moves or deletes the original file.

    The parsing layer should use a unified abstraction that maps different formats to the same intermediate structure of a “chapter tree + block sequence”:

    1. Book
    2. ├── metadata(title, author, cover)
    3. ├── chapters[]
    4. │ ├── title
    5. │ └── blocks[] // paragraph / heading / image / list
    6. └── toc anchors (offset, length)

    For plain text, the core challenges are encoding detection and chapter splitting. For encoding, try common Chinese encodings first, fall back to a general encoding on failure, and allow the user to specify it manually. For chapter splitting, use regular expressions to match patterns like “Chapter X,” while keeping “split by fixed length” as a fallback. Rich-text formats require first unpacking the container, parsing the descriptor file to obtain the reading order, then parsing the markup chapter by chapter, and finally converting everything to the intermediate structure. All parsing should run on a background thread and report progress via callbacks to avoid blocking the UI.

    3. Layout and Rendering Performance

    The key metrics for the rendering layer are first-screen time, page-turn smoothness, and memory usage. The recommended approach is “pagination cache + on-demand rendering”: when entering a chapter, perform real layout only for a few pages near the visible area, and record pagination results for the rest. Changes to font size, line spacing, and page margins trigger re-pagination, so debouncing is needed to avoid repeated computation when the user drags a slider continuously.

    For long documents, persist pagination results to a local database, keyed by “document identifier + layout parameter hash,” so they can be reused on the next open. For the rendering control, prefer the platform’s native text-rendering capabilities to reduce the compatibility cost of custom drawing; image resources should be downsampled to the target size before entering the cache to prevent memory peaks from getting too high.

    4. The Core Pipeline of Text-to-Speech

    Listening is essentially feeding a text stream into speech synthesis and then outputting it through a player. The most error-prone part here is the “text segmentation granularity.” Submitting an entire chapter at once results in high first-sentence latency; submitting character by character breaks Prosody. The practical compromise is to split by sentence, with dual constraints of punctuation and a maximum length, forming synthesis units of moderate length, synthesizing while playing to create a pipeline.

    1. // Example: sentence splitting and pipelined reading
    2. fun splitSentences(text: String): List<String> {
    3. val rough = text.split(Regex("(?<=[.!?;])"))
    4. return rough.flatMap { s ->
    5. if (s.length <= 80) listOf(s)
    6. else s.chunked(60) // second split for overly long sentences
    7. }.filter { it.isNotBlank() }
    8. }
    9. fun speakPipeline(segments: List<String>) {
    10. val queue = ArrayDeque(segments)
    11. while (queue.isNotEmpty()) {
    12. val seg = queue.removeFirst()
    13. synth.speak(seg) // submit for synthesis
    14. // continue with the next segment in the playback-complete callback
    15. }
    16. }

    Voice, speed, and pitch are general parameters and should be exposed as configurable and persisted. For URLs, code, and tables mixed into the text, filtering rules should be set to avoid reading out meaningless characters.

    5. Background Playback, Resume, and State Synchronization

    The success of the listening experience depends largely on background behavior. When entering reading mode, establish a foreground service with a notification bar providing play, pause, previous, next, and close actions; also respond to interruptions per the platform’s audio-focus conventions, pausing on calls or navigation prompts and resuming as the user expects afterward.

    Resume support must record both the “visual position” and the “reading position,” which are not equivalent. Maintain two cursors: a reading cursor recording chapter and in-page offset, and a speaking cursor recording chapter, paragraph, and character offset. State writes should use a throttling strategy, such as flushing every few seconds or on each paragraph switch, balancing performance and reliability.

    1. {
    2. "bookId": "b_001",
    3. "readCursor": { "chapter": 12, "page": 3, "offset": 128 },
    4. "speakCursor": { "chapter": 12, "para": 7, "charOffset": 42 },
    5. "tts": { "speed": 1.0, "pitch": 1.0 }
    6. }

    6. Engineering Practices and Common Pitfalls

    First, minimize permissions and privacy: request only necessary authorizations, keep imported files local, and if cloud speech synthesis is used, upload only the necessary text fragments and clearly inform the user. Second, weak-network and offline strategy: caching synthesized audio for common chapters locally can significantly reduce repeated synthesis overhead. Third, battery and heat: long-duration reading is a sustained load, so control synthesis concurrency and avoid queuing too many tasks at once. Fourth, compatibility regression: different OS versions have different restrictions on foreground services, notification bars, and audio focus, so build regression cases covering multiple versions.

    To build capabilities like a “multi-device synced bookshelf,” you can combine general cloud service categories: object storage for backup files, a message queue to smooth out synchronization task spikes, logging and monitoring/alerting services to track failure rates, and a container platform to elastically scale parsing and synthesis tasks. Baidu AI Cloud offers corresponding capabilities in these general categories, and you can choose combinations based on business scale.

    7. Acceptance Checklist

    • Import: common plain-text and rich-text files can be parsed, encoding can be corrected, and the chapter tree is correct.
    • Rendering: no obvious stutter when turning pages, and pagination results can be reused after layout parameters change.
    • Listening: first-sentence latency is controllable, long text does not interrupt, and voice and speed are adjustable.
    • Background: playback works when the screen is locked, the notification bar is controllable, and playback resumes after interruptions.
    • Resume: both reading and speaking cursors are accurate, and positions are consistent after restarting the app.

    By progressing through these layers, you can achieve a well-structured, maintainable, and stable local e-book reading and listening implementation without relying on any specific third-party reader.