Python 如何将 .wav 文件拆分为多个 .wav 文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37999150/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to split a .wav file into multiple .wav files?
提问by jdsto
I have a .wav file several minutes long that I would like to split into different 10 second .wav files.
我有一个几分钟长的 .wav 文件,我想将其拆分为不同的 10 秒 .wav 文件。
This is my python code so far:
到目前为止,这是我的python代码:
import wave
import math
def main(filename, time):
read = wave.open(filename, 'r')
#get sample rate
frameRate = read.getframerate()
#get number of frames
numFrames = read.getnframes()
#get duration
duration = numFrames/frameRate
#get all frames as a string of bytes
frames = read.readframes(numFrames)
#get 1 frame as a string of bytes
oneFrame = read.readframes(1)
#framerate*time == numframesneeded
numFramesNeeded=frameRate*time
#numFramesNeeded*oneFrame=numBytes
numBytes = numFramesNeeded*oneFrame
#splice frames to get a list strings each representing a 'time' length
#wav file
x=0
wavList=[]
while x+time<=duration:
curFrame= frames[x:x+time]
x=x+time
wavList.append(curFrame)
Printing wavList
yields:
印刷wavList
产量:
['\x00\x00\x00\x00\xff\xff\x00\x00\x00\x00', '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00']
['\x00\x00\x00\x00\xff\xff\x00\x00\x00\x00', '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00']
I know that this is a list of frames. How do I make one wav file for each element in this list (the first .wav file would be '\x00\x00\x00\x00\xff\xff\x00\x00\x00\x00'
? Python's wave
module is unclear about using frames to create .wav files.
我知道这是一个框架列表。如何为此列表中的每个元素制作一个 wav 文件(第一个 .wav 文件将是'\x00\x00\x00\x00\xff\xff\x00\x00\x00\x00'
?Python 的wave
模块不清楚使用框架创建 .wav 文件。
EDIT: This is a duplicate question of How to splice an audio file (wav format) into 1 sec splices in python?However, if someone has an answer that does not require pydub
I would very much like to see it.
编辑:这是如何在 python 中将音频文件(wav 格式)拼接成 1 秒拼接的重复问题?但是,如果有人有不需要的答案,pydub
我非常希望看到它。
回答by siddhantsomani
This is a python code snippet that I use for splitting files as per necessity.
I use the pydub library from https://github.com/jiaaro/pydub.
You can modify the snippet to suit your requirement.
这是一个 python 代码片段,我用于根据需要拆分文件。
我使用来自https://github.com/jiaaro/pydub的 pydub 库。您可以修改代码段以满足您的要求。
from pydub import AudioSegment
t1 = t1 * 1000 #Works in milliseconds
t2 = t2 * 1000
newAudio = AudioSegment.from_wav("oldSong.wav")
newAudio = newAudio[t1:t2]
newAudio.export('newSong.wav', format="wav") #Exports to a wav file in the current path.