server.py 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. import time
  2. from fastapi import FastAPI, HTTPException
  3. from fastapi.responses import StreamingResponse
  4. app = FastAPI()
  5. @app.get("/")
  6. def read_root():
  7. return {"Hello": "World"}
  8. def generate_audio():
  9. try:
  10. for chunk in get_mp3_chunks():
  11. yield chunk
  12. except FileNotFoundError:
  13. # 文件不存在时,返回 404 错误
  14. raise HTTPException(status_code=404, detail="Audio file not found")
  15. except Exception as e:
  16. # 其他错误,返回 500 错误
  17. raise HTTPException(status_code=500, detail=f"An error occurred: {e}")
  18. @app.get('/audio')
  19. async def audio_stream():
  20. return StreamingResponse(generate_audio(), media_type='audio/mpeg')
  21. def get_mp3_chunks():
  22. try:
  23. with open('assets/西海情歌-刀郎~铃声.mp3', 'rb') as f: # 使用相对路径
  24. while True:
  25. chunk = f.read(4096)
  26. if not chunk:
  27. break
  28. time.sleep(0.1)
  29. yield chunk
  30. except FileNotFoundError:
  31. raise # 重新抛出异常,由 generate_audio() 函数处理