Python实现轻松切割MP3文件

  import subprocess

  import wx

  class MyFrame(wx.Frame):

  def __init__(self, parent, title):

  super(MyFrame, self).__init__(parent, title=title, size=(400, 600))

  panel = wx.Panel(self)

  vbox = wx.BoxSizer(wx.VERTICAL)

  hbox1 = wx.BoxSizer(wx.HORIZONTAL)

  start_label = wx.StaticText(panel, label='开始时间(秒):')

  hbox1.Add(start_label, flag=wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5)

  self.start_input = wx.TextCtrl(panel)

  hbox1.Add(self.start_input, flag=wx.ALL, border=5)

  vbox.Add(hbox1, flag=wx.EXPAND | wx.ALL, border=10)

  hbox2 = wx.BoxSizer(wx.HORIZONTAL)

  end_label = wx.StaticText(panel, label='结束时间(秒):')

  hbox2.Add(end_label, flag=wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5)

  self.end_input = wx.TextCtrl(panel)

  hbox2.Add(self.end_input, flag=wx.ALL, border=5)

  vbox.Add(hbox2, flag=wx.EXPAND | wx.ALL, border=10)

  hbox3 = wx.BoxSizer(wx.HORIZONTAL)

  btn_browse = wx.Button(panel, label='选择文件', size=(100, 30))

  btn_browse.Bind(wx.EVT_BUTTON, self.on_browse)

  hbox3.Add(btn_browse, flag=wx.ALL, border=5)

  vbox.Add(hbox3, flag=wx.ALIGN_CENTER | wx.ALL, border=10)

  hbox4 = wx.BoxSizer(wx.HORIZONTAL)

  name_label = wx.StaticText(panel, label='歌名:')

  hbox4.Add(name_label, flag=wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5)

  self.name_input = wx.TextCtrl(panel)

  hbox4.Add(self.name_input, flag=wx.ALL, border=5)

  vbox.Add(hbox4, flag=wx.EXPAND | wx.ALL, border=10)

  hbox5 = wx.BoxSizer(wx.HORIZONTAL)

  btn_cut = wx.Button(panel, label='切割', size=(100, 30))

  btn_cut.Bind(wx.EVT_BUTTON, self.on_cut)

  hbox5.Add(btn_cut, flag=wx.ALL, border=5)

  vbox.Add(hbox5, flag=wx.ALIGN_CENTER | wx.ALL, border=10)

  panel.SetSizer(vbox)

  self.Show()

  def on_browse(self, event):

  dlg = wx.FileDialog(self, "选择MP3文件", wildcard="MP3文件 (*.mp3)|*.mp3", style=wx.FD_OPEN | wx.FD_FILE_MUST_EXIST)

  if dlg.ShowModal() == wx.ID_OK:

  selected_file = dlg.GetPath()

  self.input_file = selected_file

  dlg.Destroy()

  def on_cut(self, event):

  start_time = self.start_input.GetValue()

  end_time = self.end_input.GetValue()

  name = self.name_input.GetValue()

  if not start_time or not end_time or not name or not hasattr(self, 'input_file'):

  wx.MessageBox('请输入有效的开始时间、结束时间、歌名,并选择要切割的MP3文件!', '错误', wx.OK | wx.ICON_ERROR)

  return

  output_file = f'{name}.mp3'

  # 使用FFmpeg切割音频文件

  cmd = f'D://ffmpeg//bin//ffmpeg -i {self.input_file} -ss {start_time} -to {end_time} -c copy {output_file}'

  print(cmd)

  try:

  subprocess.call(cmd, shell=True)

  wx.MessageBox('切割成功!', '提示', wx.OK | wx.ICON_INFORMATION)

  except subprocess.CalledProcessError:

  wx.MessageBox('切割失败,请检查输入的时间是否正确!', '错误', wx.OK | wx.ICON_ERROR)

  app = wx.App()

  MyFrame(None, title='MP3切割工具')

  app.MainLoop()