如何使用 python 连接两个 wav 文件?

发布于 2024-09-02 18:33:27 字数 312 浏览 10 评论 0原文

我正在使用 python 编程语言,我想将 wav 文件加入到其他 wav 文件的末尾? 我在论坛上有一个问题,建议如何合并两个 wav 文件,即在某个偏移处添加一个 wav 文件的内容,但我想在彼此的末尾加入两个 wav 文件...

而且我也遇到了一个问题播放我自己的wav文件,使用winsound模块..我能够播放声音,但在播放任何Windows声音之前使用时间。睡眠一定时间,缺点是如果我想播放比时间更长的声音。睡眠(N),N秒也,Windows声音将在N秒播放winsound并停止后重叠..

任何人都可以帮忙吗?请建议如何解决这些问题...

提前致谢

I am using python programming language,I want to join to wav file one at the end of other wav file?
I have a Question in the forum which suggest how to merge two wav file i.e add the contents of one wav file at certain offset,but i want to join two wav file at the end of each other...

And also i had a prob playing the my own wav file,using winsound module..I was able to play the sound but using the time.sleep for certain time before playin any windows sound,disadvantage wit this is if i wanted to play a sound longer thn time.sleep(N),N sec also,the windows sound wil jst overlap after N sec play the winsound nd stop..

Can anyone help??please kindly suggest to how to solve these prob...

Thanks in advance

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

战皆罪 2024-09-09 18:33:27

Python 附带的 wave 模块可以满足您的需要。当文件的详细信息(单声道或立体声、帧速率等)相同时,下面的示例有效:

import wave

infiles = ["sound_1.wav", "sound_2.wav"]
outfile = "sounds.wav"

data= []
for infile in infiles:
    w = wave.open(infile, 'rb')
    data.append( [w.getparams(), w.readframes(w.getnframes())] )
    w.close()
    
output = wave.open(outfile, 'wb')
output.setparams(data[0][0])
for i in range(len(data)):
    output.writeframes(data[i][1])
output.close()

Python ships with the wave module that will do what you need. The example below works when the details of the files (mono or stereo, frame rates, etc) are the same:

import wave

infiles = ["sound_1.wav", "sound_2.wav"]
outfile = "sounds.wav"

data= []
for infile in infiles:
    w = wave.open(infile, 'rb')
    data.append( [w.getparams(), w.readframes(w.getnframes())] )
    w.close()
    
output = wave.open(outfile, 'wb')
output.setparams(data[0][0])
for i in range(len(data)):
    output.writeframes(data[i][1])
output.close()
甜宝宝 2024-09-09 18:33:27

我是 pydub 的维护者,它的设计就是为了让这类事情变得简单。

from pydub import AudioSegment

sound1 = AudioSegment.from_wav("/path/to/file1.wav")
sound2 = AudioSegment.from_wav("/path/to/file2.wav")

combined_sounds = sound1 + sound2
combined_sounds.export("/output/path.wav", format="wav")

注意:pydub 是 audioop 的一个轻量级包装。所以在幕后,它基本上做了 Tom10 提到的事情

I'm the maintainer of pydub, which is designed to make this sort of thing easy.

from pydub import AudioSegment

sound1 = AudioSegment.from_wav("/path/to/file1.wav")
sound2 = AudioSegment.from_wav("/path/to/file2.wav")

combined_sounds = sound1 + sound2
combined_sounds.export("/output/path.wav", format="wav")

note: pydub is a light wrapper around audioop. So behind the scenes, it's doing essentially what Tom10 mentioned

甜妞爱困 2024-09-09 18:33:27

Python 3 解决方案:
我们可以使用标准库来做到这一点,如 tom10 和 Eggbert 的答案所示。
下面是一个较短的版本:

  1. 仅写入第一个波形文件的参数。我们可以测试 wav_out 文件长度,看看我们是否还没有写入它。如果我们没有只写一次波形参数。
  2. 然后,当从 wav_in 读取帧时,将帧写入 wav_out。

    with wave.open(outfile, 'wb') as wav_out:
        对于 infiles 中的 wav_path:
            将 wave.open(wav_path, 'rb') 作为 wav_in:
                如果不是 wav_out.getnframes():
                    wav_out.setparams(wav_in.getparams())
                wav_out.writeframes(wav_in.readframes(wav_in.getnframes()))
    

Python 3 solution:
We can do this with the standard library as shown by tom10 and eggbert's answers.
Below is a shorter version:

  1. Only write the parameters for the first wave file. We can test the wav_out file length to see if we haven't yet written to it. If we haven't write the wave parameters once only.
  2. Then write frames to the wav_out as they are read from the wav_in.

    with wave.open(outfile, 'wb') as wav_out:
        for wav_path in infiles:
            with wave.open(wav_path, 'rb') as wav_in:
                if not wav_out.getnframes():
                    wav_out.setparams(wav_in.getparams())
                wav_out.writeframes(wav_in.readframes(wav_in.getnframes()))
    
摇划花蜜的午后 2024-09-09 18:33:27

只是以@tom10的答案为基础:

from contextlib import closing

with closing(wave.open(outfile, 'wb')) as output:

    # find sample rate from first file
    with closing(wave.open(wav_files[0])) as w:
        output.setparams(w.getparams())

    # write each file to output
    for infile in wav_files:
        with closing(wave.open(infile)) as w:
            output.writeframes(w.readframes(w.getnframes()))

它不是存储所有数据然后一次性写入最后,而是一点一点地写入。它还使用 contextlib.close,因此您不必关闭文件。

Just to build on @tom10's answer:

from contextlib import closing

with closing(wave.open(outfile, 'wb')) as output:

    # find sample rate from first file
    with closing(wave.open(wav_files[0])) as w:
        output.setparams(w.getparams())

    # write each file to output
    for infile in wav_files:
        with closing(wave.open(infile)) as w:
            output.writeframes(w.readframes(w.getnframes()))

Instead of storing all the data then writing it at the end in one go, it writes it bit by bit. It also uses contextlib.close so you don't have to close files.

枫林﹌晚霞¤ 2024-09-09 18:33:27

我使用了 pysox

wave模块和许多其他模块似乎不支持mu-law wavs。

pysox 要求您安装 SoX
并更新您的 PATH 以包含其安装目录。

import sox    
cbn=sox.Combiner()
sounds=[]
#PROCESS SOUND PATHS TO AN ARRAY
if len(sounds)>=2:
    print(sounds)
    cbn.build(sounds,'outputfilepath.ext','concatenate')

I used pysox

The wave module and many others don't seem to support mu-law wavs.

pysox reqs that you install SoX
and update your PATH to include the directory it's installed to.

import sox    
cbn=sox.Combiner()
sounds=[]
#PROCESS SOUND PATHS TO AN ARRAY
if len(sounds)>=2:
    print(sounds)
    cbn.build(sounds,'outputfilepath.ext','concatenate')
丢了幸福的猪 2024-09-09 18:33:27

您可以使用audiolab:

import audiolab, scipy
a, fs, enc = audiolab.wavread('file1.wav')
b, fs, enc = audiolab.wavread('file2.wav')
c = scipy.vstack((a,b))
audiolab.wavwrite(c, 'file3.wav', fs, enc)

You could use audiolab:

import audiolab, scipy
a, fs, enc = audiolab.wavread('file1.wav')
b, fs, enc = audiolab.wavread('file2.wav')
c = scipy.vstack((a,b))
audiolab.wavwrite(c, 'file3.wav', fs, enc)
蓝色星空 2024-09-09 18:33:27

我会使用 librosa.load 和 librosa.write_wav。
此处查看文档

import librosa
import numpy as np
import librosa.display

example_audio = librosa.util.example_audio_file()
x, sr = librosa.load(example_audio, duration=5)
print('shape of x ==> ' + str(x.shape))
y, sr = librosa.load(example_audio, duration=5)
print('shape of y ==> ' + str(y.shape))
z = np.append(x,y)
print('shape of x+y = z ==> ' + str(z.shape))
librosa.output.write_wav('joined_file.wav', z, sr)

z_loaded, sr = librosa.load('joined_file.wav')
print('shape of z loaded ==> ' + str(z_loaded.shape))

输出:

x 的形状 ==> (110250,)

y 的形状 ==> (110250,)

x+y = z 的形状 ==> (220500,)

加载的z形状==> (220500,)

I would use librosa.load and librosa.write_wav.
Check out the doc here

import librosa
import numpy as np
import librosa.display

example_audio = librosa.util.example_audio_file()
x, sr = librosa.load(example_audio, duration=5)
print('shape of x ==> ' + str(x.shape))
y, sr = librosa.load(example_audio, duration=5)
print('shape of y ==> ' + str(y.shape))
z = np.append(x,y)
print('shape of x+y = z ==> ' + str(z.shape))
librosa.output.write_wav('joined_file.wav', z, sr)

z_loaded, sr = librosa.load('joined_file.wav')
print('shape of z loaded ==> ' + str(z_loaded.shape))

Output:

shape of x ==> (110250,)

shape of y ==> (110250,)

shape of x+y = z ==> (220500,)

shape of z loaded ==> (220500,)

爱*していゐ 2024-09-09 18:33:27

我使用 SOX [1] 库,然后像

>>> import subprocess
>>> sound_output_path = /tmp
>>> sox_filenames = ['file.wav', 'file1.wav']
>>> subprocess.call(['sox'] + sox_filenames + ['%s/out.wav' % sound_output_path])

[1] 那样调用它 http://sox.sourceforge.net/< /a>

i use the SOX [1] library and then call it like

>>> import subprocess
>>> sound_output_path = /tmp
>>> sox_filenames = ['file.wav', 'file1.wav']
>>> subprocess.call(['sox'] + sox_filenames + ['%s/out.wav' % sound_output_path])

[1] http://sox.sourceforge.net/

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文