MySafeCode commited on
Commit
60f492b
·
verified ·
1 Parent(s): 01f6b01

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +39 -0
app.py CHANGED
@@ -40,6 +40,45 @@ def convert_mp3_to_flac(mp3_file_path, progress=gr.Progress()):
40
  error_msg = f"Conversion failed: {str(e)}"
41
  raise gr.Error(error_msg)
42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
  def get_file_stats(file_path):
44
  """Get statistics about the uploaded file"""
45
  if not file_path or not os.path.exists(file_path):
 
40
  error_msg = f"Conversion failed: {str(e)}"
41
  raise gr.Error(error_msg)
42
 
43
+ def convert_mp3_to_flac(mp3_file_path, progress=gr.Progress()):
44
+ """Convert MP3 file to 16-bit FLAC at 44.1kHz"""
45
+ try:
46
+ if not mp3_file_path:
47
+ raise ValueError("No file uploaded")
48
+
49
+ progress(0, desc="Starting conversion...")
50
+
51
+ # Read MP3 file
52
+ progress(0.2, desc="Loading MP3 file...")
53
+ audio = pydub.AudioSegment.from_mp3(mp3_file_path)
54
+
55
+ # 1. Ensure 16-bit depth
56
+ progress(0.4, desc="Converting to 16-bit PCM...")
57
+ audio = audio.set_sample_width(2) # 2 bytes = 16 bits
58
+
59
+ # 2. NEW STEP: Resample to 44.1 kHz if needed[citation:5][citation:7]
60
+ # The sample rate is stored as `frame_rate` in pydub[citation:7]
61
+ if audio.frame_rate != 44100:
62
+ progress(0.6, desc=f"Resampling from {audio.frame_rate} Hz to 44.1 kHz...")
63
+ audio = audio.set_frame_rate(44100) # Resample to the required rate
64
+
65
+ # Save as FLAC
66
+ progress(0.8, desc="Saving as 44.1kHz FLAC...")
67
+
68
+ # Create temporary file for output
69
+ with tempfile.NamedTemporaryFile(suffix='.flac', delete=False) as tmp:
70
+ flac_path = tmp.name
71
+
72
+ # Export as FLAC with explicit parameters
73
+ audio.export(flac_path, format="flac", parameters=["-sample_fmt", "s16", "-ar", "44100"])
74
+
75
+ progress(1.0, desc="Conversion complete!")
76
+ return flac_path
77
+
78
+ except Exception as e:
79
+ raise gr.Error(f"Conversion failed: {str(e)}")
80
+
81
+
82
  def get_file_stats(file_path):
83
  """Get statistics about the uploaded file"""
84
  if not file_path or not os.path.exists(file_path):