找回密码
 注册账号
搜索
查看: 49|回复: 0

[技巧] 使用Python获取文件夹中的mp3文件,并生成podcast的中间层

[复制链接]

3295

主题

701

回帖

3万

积分

管理员

积分
34377

最佳新人活跃会员热心会员推广达人宣传达人灌水之王突出贡献优秀版主荣誉管理论坛元老

发表于 2025.12.27 14:14 | 显示全部楼层 |阅读模式
最终效果是这样:https://www.chatcyf.com/topics/21823/

包含子目录的

  1. import os
  2. import uuid
  3. import urllib.parse
  4. from email.utils import formatdate

  5. # ==============================
  6. # 配置区域(需要修改)
  7. # ==============================
  8. AUDIO_DIR = r"\\ipfs\download\a"   # 注意:不要以 \ 结尾
  9. BASE_URL = "https://67373.chatcyf.com/a/"   # 末尾务必加 /
  10. OUTPUT_FILE = "items.xml"

  11. # ==============================
  12. # 工具函数:安全拼接 URL 路径
  13. # ==============================
  14. def build_url(base_url, relative_path):
  15.     """
  16.     将本地相对路径转换为 URL 路径,并逐段进行 URL 编码
  17.     """
  18.     parts = relative_path.replace("\", "/").split("/")
  19.     encoded_parts = [urllib.parse.quote(p) for p in parts]
  20.     return base_url + "/".join(encoded_parts)

  21. # ==============================
  22. # 生成 item 列表
  23. # ==============================
  24. items_output = ""

  25. for root, dirs, files in os.walk(AUDIO_DIR):
  26.     for filename in files:
  27.         if not filename.lower().endswith(".mp3"):
  28.             continue

  29.         full_path = os.path.join(root, filename)

  30.         # 计算相对 AUDIO_DIR 的路径(包含子目录)
  31.         relative_path = os.path.relpath(full_path, AUDIO_DIR)

  32.         # 生成完整 URL(自动带子目录)
  33.         file_url = build_url(BASE_URL, relative_path)

  34.         # 文件大小
  35.         length = os.path.getsize(full_path)

  36.         # GUID
  37.         guid = str(uuid.uuid4())

  38.         # pubDate 使用文件修改时间
  39.         timestamp = os.path.getmtime(full_path)
  40.         pub_date = formatdate(timestamp, usegmt=True)

  41.         # 标题为文件名(去后缀)
  42.         title = os.path.splitext(filename)[0]

  43.         item = f"""
  44.     <item>
  45.         <title>{title}</title>
  46.         <description><![CDATA[{title}]]></description>
  47.         <enclosure url="{file_url}" length="{length}" type="audio/mpeg" />
  48.         <guid>{guid}</guid>
  49.         <pubDate>{pub_date}</pubDate>
  50.         <itunes:explicit>no</itunes:explicit>
  51.     </item>
  52.     """

  53.         items_output += item

  54. # ==============================
  55. # 保存结果
  56. # ==============================
  57. with open(OUTPUT_FILE, "w", encoding="utf-8") as f:
  58.     f.write(items_output)

  59. print(f"音频 item 已生成:{OUTPUT_FILE}")
复制代码


不包含子目录的代码

  1. import os
  2. import uuid
  3. import urllib.parse
  4. from datetime import datetime
  5. from email.utils import formatdate

  6. # ==============================
  7. # 配置区域(需要修改)
  8. # ==============================
  9. AUDIO_DIR = r"\\ipfs\download\email"   # 本地 mp3 文件夹
  10. BASE_URL = "https://67373.chatcyf.com/Douyu/email/"   # 在线 URL 前缀,末尾务必加 /
  11. OUTPUT_FILE = "items.xml"   # 最终生成 item 列表

  12. # ==============================
  13. # 生成 item 列表
  14. # ==============================
  15. items_output = ""

  16. for filename in os.listdir(AUDIO_DIR):
  17.     if not filename.lower().endswith(".mp3"):
  18.         continue

  19.     full_path = os.path.join(AUDIO_DIR, filename)

  20.     # 获取真实文件大小(字节)
  21.     length = os.path.getsize(full_path)

  22.     # URL encode 处理
  23.     encoded_name = urllib.parse.quote(filename)
  24.     file_url = BASE_URL + encoded_name

  25.     # GUID 使用 UUID,绝对不会重复
  26.     guid = str(uuid.uuid4())

  27.     # 使用文件修改时间作为 pubDate
  28.     timestamp = os.path.getmtime(full_path)
  29.     pub_date = formatdate(timestamp, usegmt=True)

  30.     # 标题为文件名去掉后缀
  31.     title = os.path.splitext(filename)[0]

  32.     item = f"""
  33.     <item>
  34.         <title>{title}</title>
  35.         <description><![CDATA[{title}]]></description>
  36.         <enclosure url="{file_url}" length="{length}" type="audio/mpeg" />
  37.         <guid>{guid}</guid>
  38.         <pubDate>{pub_date}</pubDate>
  39.         <itunes:explicit>no</itunes:explicit>
  40.     </item>
  41.     """

  42.     items_output += item

  43. # 保存结果
  44. with open(OUTPUT_FILE, "w", encoding="utf-8") as f:
  45.     f.write(items_output)

  46. print(f"音频 item 已生成:{OUTPUT_FILE}")
复制代码


视频和音频都有,分别的

  1. import os
  2. import uuid
  3. import urllib.parse
  4. from email.utils import formatdate

  5. # ==============================
  6. # 配置区域
  7. # ==============================
  8. MEDIA_DIR = r"\\ipfs\download\67373.chatcyf.com"
  9. BASE_URL = "https://67373.chatcyf.com/"
  10. AUDIO_OUTPUT = "audio.xml"
  11. VIDEO_OUTPUT = "video.xml"

  12. # ==============================
  13. # 工具函数:生成 URL
  14. # ==============================
  15. def build_url(base_url, relative_path):
  16.     parts = relative_path.replace("\", "/").split("/")
  17.     encoded_parts = [urllib.parse.quote(p) for p in parts]
  18.     return base_url + "/".join(encoded_parts)

  19. # ==============================
  20. # item 容器
  21. # ==============================
  22. audio_items = []
  23. video_items = []

  24. # ==============================
  25. # 扫描目录
  26. # ==============================
  27. for root, dirs, files in os.walk(MEDIA_DIR):
  28.     for filename in files:
  29.         ext = os.path.splitext(filename)[1].lower()

  30.         if ext == ".mp3":
  31.             mime_type = "audio/mpeg"
  32.             target_list = audio_items
  33.         elif ext == ".mp4":
  34.             mime_type = "video/mp4"
  35.             target_list = video_items
  36.         else:
  37.             continue

  38.         full_path = os.path.join(root, filename)
  39.         relative_path = os.path.relpath(full_path, MEDIA_DIR)
  40.         file_url = build_url(BASE_URL, relative_path)

  41.         length = os.path.getsize(full_path)
  42.         guid = str(uuid.uuid4())
  43.         pub_date = formatdate(os.path.getmtime(full_path), usegmt=True)
  44.         title = os.path.splitext(filename)[0]

  45.         item = f"""
  46.     <item>
  47.         <title>{title}</title>
  48.         <description><![CDATA[{title}]]></description>
  49.         <enclosure url="{file_url}" length="{length}" type="{mime_type}" />
  50.         <guid>{guid}</guid>
  51.         <pubDate>{pub_date}</pubDate>
  52.         <itunes:explicit>no</itunes:explicit>
  53.     </item>
  54.     """

  55.         target_list.append(item)

  56. # ==============================
  57. # 写入文件
  58. # ==============================
  59. with open(AUDIO_OUTPUT, "w", encoding="utf-8") as f:
  60.     f.write("".join(audio_items))

  61. with open(VIDEO_OUTPUT, "w", encoding="utf-8") as f:
  62.     f.write("".join(video_items))

  63. print(f"音频 RSS item 生成完成:{AUDIO_OUTPUT}({len(audio_items)} 条)")
  64. print(f"视频 RSS item 生成完成:{VIDEO_OUTPUT}({len(video_items)} 条)")
复制代码



您需要登录后才可以回帖 登录 | 注册账号

本版积分规则

Archiver|手机版|小黑屋|童话镇 |网站地图

GMT+8, 2026.1.1 00:59 , Processed in 0.031094 second(s), 2 queries , Gzip On, Redis On.

Powered by Discuz! X3.5

© 2001-2025 Discuz! Team.

快速回复 返回顶部 返回列表