### Install react-native-transcript-karaoke Source: https://github.com/rossyman/react-native-transcript-karaoke/blob/main/README.md Installs the react-native-transcript-karaoke package using npm. This is the first step to integrating the karaoke component into your React Native project. ```bash npm install react-native-transcript-karaoke ``` -------------------------------- ### Handle Errors in React Native Karaoke Component Source: https://context7.com/rossyman/react-native-transcript-karaoke/llms.txt This example shows how to use a try-catch block to handle errors thrown by the SimpleParser when processing invalid or malformed transcript data. It displays error messages to the user if parsing fails. ```tsx import { Karaoke, SimpleParser } from 'react-native-transcript-karaoke' import { useState } from 'react' function ErrorHandlingExample() { const [error, setError] = useState(null) const [progress, setProgress] = useState(0) // Valid transcript const validTranscript = ` [00:00:03] Valid line [00:00:07] Another valid line ` // Invalid transcripts that will throw errors const invalidTimestamp = ` [99:99:99] Invalid time [00:00:05] Valid line ` const malformedFormat = ` 00:00:03 Missing brackets [00:00:05] Valid line ` const missingTimestamp = ` Just text without timestamp [00:00:05] Valid line ` const renderKaraoke = (transcript: string) => { try { const parser = new SimpleParser('seconds') const parsed = parser.parse(transcript) return ( ) } catch (err) { const errorMessage = err instanceof Error ? err.message : 'Unknown error' setError(errorMessage) return null } } return ( <> {error && ( Error: {error} )} {renderKaraoke(validTranscript)} {/* These will throw errors: - invalidTimestamp: "The following timestamp is incorrectly formatted: 99:99:99" - malformedFormat: "The following line is incorrectly formatted: 00:00:03 Missing brackets" - missingTimestamp: "The following line is incorrectly formatted: Just text without timestamp" */} ) } ``` -------------------------------- ### Karaoke Component API Definition Source: https://github.com/rossyman/react-native-transcript-karaoke/blob/main/README.md Defines the TypeScript interface for the Karaoke component's props. It outlines required and optional properties such as transcript content, audio progress, styling options, a custom parser, and a seek event handler. This interface guides developers on how to configure and use the component effectively. ```typescript interface KaraokeProps { /** * The transcript we wish to provide karaoke styling for */ transcript: string /** * The current progress of the audio track being played */ progress: number /** * The format that the current progress is given in */ progressType?: ProgressType /** * The base style we wish to apply to the displayed transcript */ style?: StyleProp /** * The style we wish to apply to previous and current chunks of * the transcript */ activeStyle?: StyleProp /** * The parser we wish to use to parse the transcript */ parser?: Parser /** * Exposes `onPress` events from chunks * * @param seekTo The duration the user has indicated they want to seek to */ onSeekTo?: (seekTo: number) => void } ``` -------------------------------- ### Karaoke Component with Seconds Progress Type using react-native-track-player Source: https://context7.com/rossyman/react-native-transcript-karaoke/llms.txt Illustrates integrating the Karaoke component with `react-native-track-player` to synchronize lyrics with audio playback. The `progressType` is set to 'seconds', matching the output of `useProgress()` from `react-native-track-player`. This setup is suitable for applications using this specific audio player library. ```tsx import { Karaoke, ProgressType } from 'react-native-transcript-karaoke' import { useProgress } from 'react-native-track-player' function TrackPlayerIntegration() { // react-native-track-player returns progress in seconds const { position } = useProgress() const transcript = ` [00:00:00.500] First line starts at half second [00:00:05.250] Second line at 5.25 seconds [00:00:10.750] Third line at 10.75 seconds ` return ( ) } ``` -------------------------------- ### Basic Karaoke Component Implementation in React Native Source: https://context7.com/rossyman/react-native-transcript-karaoke/llms.txt Demonstrates the core usage of the Karaoke component to display synchronized lyrics based on simulated audio playback progress. It takes a transcript string, current playback progress, and styling options for active and base text. The `onSeekTo` prop allows for interactive seeking within the transcript. ```tsx import React, { useState, useEffect } from 'react' import { View, TextStyle } from 'react-native' import { Karaoke } from 'react-native-transcript-karaoke' function MusicPlayer() { const [progress, setProgress] = useState(0) const transcript = ` [00:00:03] Tell me something I need to know [00:00:07] Then take my breath and never let it go [00:00:12] If you just let me invade your space [00:00:17] I'll take the pleasure, take it with the pain [00:00:22] And if in the moment, I bite my lip [00:00:27] Baby, in that moment, you'll know this is [00:00:32] Something bigger than us and beyond bliss [00:00:37] Give me a reason to believe it ` // Simulate playback progress (in real app, sync with audio player) useEffect(() => { const interval = setInterval(() => { setProgress(prev => prev + 1) }, 1000) return () => clearInterval(interval) }, []) const baseStyle: TextStyle = { fontSize: 24, fontWeight: '600', color: '#666666', paddingBottom: 12, lineHeight: 32 } const activeStyle: TextStyle = { color: '#1DB954', fontWeight: '700' } const handleSeek = (seekTo: number) => { setProgress(seekTo) // In real app: audioPlayer.seekTo(seekTo) } return ( ) } export default MusicPlayer ``` -------------------------------- ### Use SimpleParser and Extended Utility Methods Source: https://context7.com/rossyman/react-native-transcript-karaoke/llms.txt Demonstrates the direct use of the built-in SimpleParser for parsing transcripts with a standard format like '[00:00:03] text'. It also shows how to extend SimpleParser to access and utilize its protected utility methods for more complex timestamp manipulations and conversions. ```tsx import { SimpleParser, ProgressType } from 'react-native-transcript-karaoke' // Using the default SimpleParser directly const parser = new SimpleParser('seconds') const transcript = ` [00:00:03] First line [00:00:07.500] Second line with milliseconds [00:01:15] Third line at 1 minute 15 seconds ` try { const parsed = parser.parse(transcript) // parsed = [ // { start: 3, transcript: "First line" }, // { start: 7.5, transcript: "Second line with milliseconds" }, // { start: 75, transcript: "Third line at 1 minute 15 seconds" } // ] parsed.forEach(chunk => { console.log(`At ${chunk.start}s: ${chunk.transcript}`) }) } catch (error) { console.error('Invalid transcript format:', error.message) } // Using milliseconds instead const msParser = new SimpleParser('milliseconds') const msTranscript = '[00:00:03.250] Line at 3250 milliseconds' const msParsed = msParser.parse(msTranscript) // msParsed = [{ start: 3250, transcript: "Line at 3250 milliseconds" }] // Extended parser example with utility methods class ExtendedParser extends SimpleParser { // Access protected utility methods parseCustomFormat(timestamp: string, text: string) { const [hrs, mins, secs, millis] = this.toDurations(timestamp) return { hours: hrs, minutes: mins, seconds: secs, milliseconds: millis, totalSeconds: this.toSeconds(hrs, mins, secs), totalMilliseconds: this.toMilliseconds(hrs, mins, secs, millis), text: text } } } const extendedParser = new ExtendedParser('seconds') const result = extendedParser.parseCustomFormat('01:30:45.500', 'Example text') // result = { // hours: 1, minutes: 30, seconds: 45, milliseconds: 500, // totalSeconds: 5445, totalMilliseconds: 5445500, // text: "Example text" // } ``` -------------------------------- ### Interactive Seeking with onSeekTo in React Native Source: https://context7.com/rossyman/react-native-transcript-karaoke/llms.txt Implements user interaction with transcript chunks to seek within media playback. It utilizes `onSeekTo` callback to handle seek events, integrating with `react-native-track-player` for actual media seeking. The `useProgress` hook from `react-native-track-player` provides the current playback position. ```tsx import { Karaoke } from 'react-native-transcript-karaoke' import TrackPlayer from 'react-native-track-player' import { useProgress } from 'react-native-track-player' function InteractiveKaraoke() { const { position } = useProgress() const transcript = ` [00:00:00] Intro line [00:00:05] First verse [00:00:15] Second verse [00:00:25] Chorus begins [00:00:45] Chorus ends [00:01:00] Bridge section ` const handleSeek = async (seekTo: number) => { try { // Seek to the exact timestamp in the audio player await TrackPlayer.seekTo(seekTo) console.log(`Seeking to ${seekTo} seconds`) } catch (error) { console.error('Seek failed:', error) } } return ( ) } // Example with custom seek behavior function CustomSeekBehavior() { const [progress, setProgress] = useState(0) const [seekHistory, setSeekHistory] = useState([]) const transcript = '[00:00:05] Line one\n[00:00:10] Line two\n[00:00:15] Line three' const handleSeekWithTracking = (seekTo: number) => { // Custom logic before seeking setSeekHistory(prev => [...prev, seekTo]) setProgress(seekTo) // Track analytics console.log(`User seeked to ${seekTo}s`) console.log(`Total seeks: ${seekHistory.length + 1}`) // Could also prevent seeking to certain sections if (seekTo < 5) { console.warn('Cannot seek before intro') return } // Perform actual seek setProgress(seekTo) } return ( ) } ``` -------------------------------- ### Basic Karaoke Component Usage in React Native Source: https://github.com/rossyman/react-native-transcript-karaoke/blob/main/README.md Demonstrates the basic usage of the Karaoke component. It requires a transcript string, the current audio progress, and the type of progress (seconds or milliseconds). Active styling can be applied to highlight current and past text chunks. Dependencies include React Native and potentially react-native-track-player for audio playback. ```tsx const transcript = ` [00:00:03] Tell me something I need to know [00:00:07] Then take my breath and never let it go [00:00:12] If you just let me invade your space [00:00:17] I'll take the pleasure, take it with the pain [00:00:22] And if in the moment, I bite my lip [00:00:27] Baby, in that moment, you'll know this is [00:00:32] Something bigger than us and beyond bliss [00:00:37] Give me a reason to believe it ` ``` -------------------------------- ### Implement Custom SRT and Simple Parsers Source: https://context7.com/rossyman/react-native-transcript-karaoke/llms.txt Demonstrates the creation of custom parsers extending the base Parser class for SRT and a simple timestamp format. These parsers handle specific transcript structures and timestamp formats, converting them into a ParsedTranscript array. They are then used within the Karaoke component. ```tsx import { Parser, ParsedTranscript, ProgressType } from 'react-native-transcript-karaoke' // Custom parser for SRT subtitle format class SRTParser extends Parser { protected NEW_CHUNK_REGEX = /\n\n/ // SRT format: // 1 // 00:00:03,000 --> 00:00:07,000 // First subtitle line parse(transcript: string): ParsedTranscript { const chunks = this.toChunks(transcript) return chunks.map(chunk => { const lines = chunk.split('\n') const timeLine = lines[1] const text = lines.slice(2).join(' ') // Parse "00:00:03,000 --> 00:00:07,000" const [startStr, endStr] = timeLine.split(' --> ') const start = this.parseTimestamp(startStr) const end = this.parseTimestamp(endStr) return { start, end, transcript: text } }) } private parseTimestamp(timestamp: string): number { // Convert "00:00:03,000" to "00:00:03.000" const normalized = timestamp.replace(',', '.') return this.toTimestamp(normalized) } } // Custom parser for simple format without brackets class SimplestParser extends Parser { protected NEW_CHUNK_REGEX = /\n/ // Format: "03.5 - First line" parse(transcript: string): ParsedTranscript { return this.toChunks(transcript).map(chunk => { const [timeStr, ...textParts] = chunk.split(' - ') const seconds = parseFloat(timeStr) if (isNaN(seconds)) { throw new Error(`Invalid timestamp: ${timeStr}`) } return { start: seconds, transcript: textParts.join(' - ').trim() } }) } } function CustomParserExample() { const [progress, setProgress] = useState(0) const srtTranscript = `1 00:00:03,000 --> 00:00:07,000 Tell me something I need to know 2 00:00:07,000 --> 00:00:12,000 Then take my breath and never let it go 3 00:00:12,000 --> 00:00:17,000 If you just let me invade your space` const simpleTranscript = `3 - First line at 3 seconds 7 - Second line at 7 seconds 12 - Third line at 12 seconds` return ( <> ) } ``` -------------------------------- ### Styling and Visual Customization in React Native Karaoke Source: https://context7.com/rossyman/react-native-transcript-karaoke/llms.txt Allows configuration of the visual appearance of transcript text using React Native's `TextStyle` for both base and active states. This enables customization of font size, weight, color, background, shadows, and more, offering presets for different aesthetic styles. ```tsx import { Karaoke } from 'react-native-transcript-karaoke' import { TextStyle, StyleSheet, Animated } from 'react-native' function StyledKaraoke() { const [progress, setProgress] = useState(0) const transcript = ` [00:00:03] Style me beautifully [00:00:07] With gradients and shadows [00:00:12] Make the text pop ` // Base styling for inactive text const baseStyle: TextStyle = { fontSize: 28, fontWeight: '500', color: '#999999', paddingVertical: 8, paddingHorizontal: 12, lineHeight: 40, letterSpacing: 0.5, fontFamily: 'System', textAlign: 'center' } // Active styling for current/past lyrics const activeStyle: TextStyle = { color: '#ffffff', fontWeight: '800', backgroundColor: '#1DB954', borderRadius: 8, shadowColor: '#000', shadowOffset: { width: 0, height: 2 }, shadowOpacity: 0.3, shadowRadius: 4, elevation: 5, textShadowColor: 'rgba(0, 0, 0, 0.5)', textShadowOffset: { width: 1, height: 1 }, textShadowRadius: 3 } return ( ) } // Multiple style presets const styles = StyleSheet.create({ spotifyStyle: { fontSize: 32, fontWeight: '700', color: '#535353', lineHeight: 48 }, spotifyActive: { color: '#FFFFFF' }, karaokeStyle: { fontSize: 36, fontWeight: '900', color: '#FFD700', textAlign: 'center', textTransform: 'uppercase' }, karaokeActive: { color: '#FF1493', textDecorationLine: 'underline' }, minimalistStyle: { fontSize: 18, fontWeight: '400', color: '#000000', opacity: 0.3 }, minimalistActive: { opacity: 1, fontWeight: '600' } }) function PresetStyles() { const [progress, setProgress] = useState(0) const transcript = '[00:00:05] Styled text example' return ( <> ) } ``` -------------------------------- ### Karaoke Component API Source: https://github.com/rossyman/react-native-transcript-karaoke/blob/main/README.md The Karaoke component accepts various props to customize its behavior and appearance. These props allow you to pass in the transcript data, track audio progress, define styling for active text segments, and handle user interactions like seeking. ```APIDOC ## Karaoke Component API ### Description The `Karaoke` component displays transcript text with dynamic styling based on audio playback progress. It supports custom styling for active text segments and allows for interactivity through the `onSeekTo` prop. ### Method ``` React Component ``` ### Endpoint ``` ``` ### Parameters #### Props - **transcript** (string) - Required - The transcript string to be displayed. Lines are typically separated by new-lines, and timestamps are expected in `[HH:mm:ss]` or `[HH:mm:ss.SSS]` format. - **progress** (number) - Required - The current playback progress of the audio track. - **progressType** (ProgressType) - Optional - Specifies the unit of the `progress` prop. Can be 'seconds' (default) or 'milliseconds'. - **style** (StyleProp) - Optional - The base style to be applied to the entire transcript text. - **activeStyle** (StyleProp) - Optional - The style to be applied to the currently active and past transcript chunks. - **parser** (Parser) - Optional - A custom parser instance to handle non-standard transcript formats. If not provided, a default parser is used. - **onSeekTo** (function) - Optional - A callback function that is invoked when a user interacts with a transcript chunk, presumably to seek to a specific time. It receives the `seekTo` duration as a number. ### Request Example ```tsx import Karaoke from 'react-native-transcript-karaoke'; const transcript = ` [00:00:03] Tell me something I need to know [00:00:07] Then take my breath and never let it go `; { // Handle seeking logic, e.g., using react-native-track-player console.log('Seeking to:', seekTo); }} /> ``` ### Response No direct response data, as this is a UI component. Styling and interactivity are managed via props. #### Success Response (Component Render) - The component renders the transcript with appropriate styling based on the `progress` prop. #### Response Example (UI Rendering - No JSON response) ``` -------------------------------- ### Karaoke Component with Milliseconds Progress Type Source: https://context7.com/rossyman/react-native-transcript-karaoke/llms.txt Shows how to configure the Karaoke component to use milliseconds for tracking playback progress. This is useful for applications requiring very precise synchronization or when the audio source provides time in milliseconds. The `progressType` is explicitly set to 'milliseconds'. ```tsx import { Karaoke, ProgressType } from 'react-native-transcript-karaoke' import { useState, useEffect } from 'react' function MillisecondsExample() { const [progressMs, setProgressMs] = useState(0) const transcript = ` [00:00:00.100] Very precise timing [00:00:00.500] Half second mark [00:00:01.250] One and quarter seconds ` useEffect(() => { const interval = setInterval(() => { setProgressMs(prev => prev + 100) }, 100) return () => clearInterval(interval) }, []) return ( ) } ``` -------------------------------- ### Custom Transcript Validation Function Source: https://context7.com/rossyman/react-native-transcript-karaoke/llms.txt A utility function to validate the format and timestamp values of a transcript string before parsing. It checks for correct timestamp patterns and logical time ranges, returning validation status and any found errors. ```typescript // Validation helper function validateTranscript(transcript: string): { valid: boolean; errors: string[] } { const errors: string[] = [] const lines = transcript.trim().split('\n') const timestampRegex = /^\<0-9]{2}:[0-9]{2}:[0-9]{2}(?:\.[0-9]{3})?\]/ lines.forEach((line, index) => { const trimmed = line.trim() if (!trimmed) return const match = trimmed.match(timestampRegex) if (!match) { errors.push(`Line ${index + 1}: Invalid format - "${trimmed}"`); return } const [hrs, mins, secs] = match[1].split(/[:.]/).map(Number) if (hrs > 23 || mins > 59 || secs > 59) { errors.push(`Line ${index + 1}: Invalid timestamp values - "${match[1]}"`); } }) return { valid: errors.length === 0, errors } } // Usage const userTranscript = '[00:00:03] Test line' const validation = validateTranscript(userTranscript) if (validation.valid) { // Render Karaoke component } else { console.error('Validation errors:', validation.errors) } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.