Yinghoo commited on
Commit
1b2d5e1
·
verified ·
1 Parent(s): ed38226

Update app.py

Browse files

Solve .MP3 decode mistake

Files changed (1) hide show
  1. app.py +26 -1
app.py CHANGED
@@ -1,10 +1,27 @@
1
  import librosa
2
  import numpy as np
3
  import matplotlib.pyplot as plt
 
 
 
 
4
 
5
- def extract_melody(audio_file):
 
 
 
 
 
 
 
 
 
 
6
  # 加载音频文件
7
  y, sr = librosa.load(audio_file)
 
 
 
8
 
9
  # 提取旋律(和声成分)
10
  y_harmonic, y_percussive = librosa.effects.harmonic(y)
@@ -20,6 +37,14 @@ def extract_melody(audio_file):
20
  plt.tight_layout()
21
  plt.show()
22
 
 
 
 
 
 
 
 
 
23
  # 替换为你的音频文件路径
24
  audio_file = 'your_song.mp3'
25
  extract_melody(audio_file)
 
1
  import librosa
2
  import numpy as np
3
  import matplotlib.pyplot as plt
4
+ import librosa.display
5
+ import soundfile as sf
6
+ import os
7
+ from pydub import AudioSegment
8
 
9
+ def preprocess_audio(audio_file):
10
+ sound = AudioSegment.from_mp3(audio_file)
11
+ wav_file = audio_file.rsplit('.',1)[0]+'.wav'
12
+ sound.export(wav_file, format="wav" )
13
+ return wav_file
14
+
15
+ def extract_melody(audio_file,output_folder):
16
+ try:
17
+ # 预处理音频文件
18
+ audio_file = preprocess_audio(audio_file)
19
+
20
  # 加载音频文件
21
  y, sr = librosa.load(audio_file)
22
+
23
+ # 使用 HPSS 分离和声和打击乐成分
24
+ y_harmonic, y_percussive = librosa.effects.hpss(y)
25
 
26
  # 提取旋律(和声成分)
27
  y_harmonic, y_percussive = librosa.effects.harmonic(y)
 
37
  plt.tight_layout()
38
  plt.show()
39
 
40
+ # 保存提取的旋律
41
+ base_name = os.path.splitext(os.path.basename(audio_file))[0]
42
+ output_file = os.path.join(output_folder, f'extracted_melody_{base_name}.wav')
43
+ sf.write(output_file, y_harmonic, sr)
44
+ print(f"Extracted melody saved to: {output_file}")
45
+ except Exception as e:
46
+ print(f"An error occurred: {e}")
47
+
48
  # 替换为你的音频文件路径
49
  audio_file = 'your_song.mp3'
50
  extract_melody(audio_file)