An error occurred while playing audio:
[Errno 13] Permission denied: 'C:\Users\iqtad\AppData\Local\Temp\tmpjdxaled7.wav'
My folder has permissions to read and write in the properties. I turned off my anti virus. I even tried running the code from my command terminal and VS studio as an admin. I do not see why this keeps happening.
import subprocess
import time
from pydub import AudioSegment
from pydub.playback import play
from openai import OpenAI, OpenAIError # Import OpenAIError for handling exceptions
# Initialize the OpenAI client with your API key
client = OpenAI(api_key='XXX')
def generate_speech(text):
try:
# Generate speech using OpenAI's TTS model
process = subprocess.Popen(["curl", "https://api.openai.com/v1/audio/speech", "-H", "Authorization: Bearer XXX", "-H", "Content-Type: application/json", "-d", f'{{"model": "tts-1", "input": "{text}", "voice": "alloy"}}', "--output", "speech.mp3"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
process.wait() # Wait for the process to finish
if process.returncode == 0:
return "speech.mp3"
else:
print("Error generating speech.")
return None
except Exception as e:
print("An error occurred:", e)
return None
def play_audio(file_path):
try:
audio = AudioSegment.from_mp3(file_path)
play(audio)
except Exception as e:
print("An error occurred while playing audio:", e)
def interactive_chat():
# Start with a system message defining the assistant's role
conversation_history = [{"role": "system", "content": " You are a marine biologist"}]
while True:
user_message = input("You: ").strip()
if user_message.lower() == "quit":
print("Ending the chat session.")
break
if user_message:
conversation_history.append({"role": "user", "content": user_message})
else:
print("Message is empty, please enter some text.")
continue
try:
completion = client.chat.completions.create(
model="gpt-4",
messages=conversation_history
)
# Correctly extracting and trimming the AI's response content
ai_response_content = completion.choices[0].message.content.strip() # Adjusted to correctly access 'content'
if ai_response_content:
print("AI:", ai_response_content)
conversation_history.append({"role": "assistant", "content": ai_response_content})
# Generate speech for AI response
speech_file = generate_speech(ai_response_content)
if speech_file:
# Play the generated speech
play_audio(speech_file)
else:
print("Failed to generate speech for AI response.")
else:
print("AI response was empty.")
except OpenAIError as e:
print(f"An error occurred: {e}")
break
# Start the interactive chat
interactive_chat()
How can I resolve this to make my code work? I don’t know how to fix this error.
1