import streamlit as st from openai import OpenAI import os from pathlib import Path import base64 def create_audio_player(audio_path): """Create an HTML audio player for the generated audio file""" audio_file = open(audio_path, 'rb') audio_bytes = audio_file.read() audio_base64 = base64.b64encode(audio_bytes).decode() audio_player = f'' return audio_player def main(): st.title("🗣️ Text to Speech with OpenAI") # Sidebar for API key with st.sidebar: st.header("Configuration") api_key = st.text_input("Enter your OpenAI API key", type="password") st.markdown(""" ### How to get an API key 1. Go to [OpenAI API Keys](https://platform.openai.com/api-keys) 2. Create a new secret key 3. Copy and paste it here """) # Main content st.markdown("Convert your text to natural-sounding speech using OpenAI's TTS API.") # Text input user_input = st.text_area("Enter the text you want to convert to speech:", height=150, placeholder="Enter your text here...") # Voice selection voice_option = st.selectbox( "Select a voice:", ["alloy", "echo", "fable", "onyx", "nova", "shimmer"] ) # Create a button to generate audio if st.button("Generate Speech"): if not api_key: st.error("Please enter your OpenAI API key in the sidebar.") return if not user_input: st.error("Please enter some text to convert to speech.") return try: # Show spinning indicator while processing with st.spinner("Generating audio..."): # Initialize OpenAI client with the API key client = OpenAI(api_key=api_key) # Create output directory if it doesn't exist output_dir = Path("generated_audio") output_dir.mkdir(exist_ok=True) # Generate unique filename output_file = output_dir / "output.mp3" # Generate speech response = client.audio.speech.create( model="tts-1", voice=voice_option, input=user_input ) # Save the audio file response.stream_to_file(str(output_file)) # Display success message st.success("Audio generated successfully!") # Create and display audio player st.markdown("### Listen to the generated audio:") st.markdown(create_audio_player(output_file), unsafe_allow_html=True) # Add download button with open(output_file, "rb") as file: st.download_button( label="Download Audio", data=file, file_name="generated_speech.mp3", mime="audio/mp3" ) except Exception as e: st.error(f"An error occurred: {str(e)}") if __name__ == "__main__": main()