| 12345678910111213141516171819202122232425262728293031323334353637 |
- import time
- from fastapi import FastAPI, HTTPException
- from fastapi.responses import StreamingResponse
- app = FastAPI()
- @app.get("/")
- def read_root():
- return {"Hello": "World"}
- def generate_audio():
- try:
- for chunk in get_mp3_chunks():
- yield chunk
- except FileNotFoundError:
- # 文件不存在时,返回 404 错误
- raise HTTPException(status_code=404, detail="Audio file not found")
- except Exception as e:
- # 其他错误,返回 500 错误
- raise HTTPException(status_code=500, detail=f"An error occurred: {e}")
- @app.get('/audio')
- async def audio_stream():
- return StreamingResponse(generate_audio(), media_type='audio/mpeg')
- def get_mp3_chunks():
- try:
- with open('assets/西海情歌-刀郎~铃声.mp3', 'rb') as f: # 使用相对路径
- while True:
- chunk = f.read(4096)
- if not chunk:
- break
- time.sleep(0.1)
- yield chunk
- except FileNotFoundError:
- raise # 重新抛出异常,由 generate_audio() 函数处理
|