Music & Python

파이썬으로 m4a 파일 wav 변환하기 (m4a to wav for Python)

Le Hayyim 2023. 8. 16. 16:09

윈도우로 녹음을 하면 m4a 파일로 녹음 되는 것을 알 수 있다. 이 파일을 wav로 바꾸는 파이썬 코드에 대해 알아보자. 먼저, pip를 통해 pydub를 설치한다. 

If you record on Windows, you can see that it is recorded as an m4a file. Let's find out about Python code that turns this file into wav. First, install a pydub through a pip.

pip install pydub

filePath를 설정해주고, AudioSegment 함수로 오디오 정보를 audio 변수에 저장한다. audio.export를 통해 변경된 이름 (m4a > wav)으로 wav 형태로 저장한다. 

Set the filePath and save the audio information to the audio variable as an audioSegment function. Save the changed name (m4a > wav) in the form of wav through audio.export.

 

이 때 filePath는 파이썬 파일이 있는 폴더에 대하여 상대 주소를 쓰거나, 절대주소를 사용한다. 

In this case, filePath writes a relative address or uses an absolute address for a folder containing Python files.

 

from pydub import AudioSegment

filePath = "밤편지.m4a"

audio = AudioSegment.from_file(filePath, format="m4a")
wavFilePath = filePath.replace("m4a", "wav")
audio.export(wavFilePath, format="wav")

함수로 변경하고, if __name__ == "__main__" 문으로 run을 했을 때 여러 파일을 wav 파일로 변환하는 과정을 수행한다. 

When you change to a function and run with the if__name__== "__main__" statement, you perform the process of converting multiple files into a wav file.

from pydub import AudioSegment

def mp4towav(filePath):
    audio = AudioSegment.from_file(filePath, format="m4a")
    wavFilePath = filePath.replace("m4a", "wav")
    audio.export(wavFilePath, format="wav")
    print(wavFilePath, "done") #확인용 출력 


if __name__ == "__main__":
    for i in ["밤편지.m4a", "밤편지 2.m4a", "밤편지 3.m4a", "밤편지 4.m4a"]:
        mp4towav(i)

* 그냥 파일 이름만 변경하는 코드로도 확장자를 바꿀 수 있으나, 여러 오류가 발생할 수 있으므로 audio.export를 통해 정식으로 파일의 확장자를 변경해주는 것이 좋다. 

* You can change the extension with code that just changes the file name, but it is recommended to change the extension of the file officially through audio.export because it can cause many errors.

결과
잘 작동한다 !!

반응형