将声音文件作为NumPy数组导入Python(audiolab的替代品)

时间:2010-03-01 15:20:55

标签: python audio numpy scipy

过去我一直在使用Audiolab导入声音文件,而且效果很好。但是:

-

In [2]: from scikits import audiolab
--------------------------------------------------------------------

ImportError                               Traceback (most recent call last)

C:\Python26\Scripts\<ipython console> in <module>()

C:\Python26\lib\site-packages\scikits\audiolab\__init__.py in <module>()
     23 __version__ = _version
     24
---> 25 from pysndfile import formatinfo, sndfile
     26 from pysndfile import supported_format, supported_endianness, \
     27                       supported_encoding, PyaudioException, \

C:\Python26\lib\site-packages\scikits\audiolab\pysndfile\__init__.py in <module>()
----> 1 from _sndfile import Sndfile, Format, available_file_formats, available_encodings
      2 from compat import formatinfo, sndfile, PyaudioException, PyaudioIOError
      3 from compat import supported_format, supported_endianness, supported_encoding

ImportError: DLL load failed: The specified module could not be found.``

所以我想要:

  • 找出为什么它不能在2.6中运行(_sndfile.pyd出错?)并且可能找到一种方法来扩展它以使用不支持的格式
  • 查找完整的audiolab替换

5 个答案:

答案 0 :(得分:11)

Audiolab正在使用Python 2.6.2在Ubuntu 9.04上为我工作,所以它可能是一个Windows问题。在您的论坛链接中,作者还建议它是Windows错误。

过去,这个选项对我也有用:

from scipy.io import wavfile
fs, data = wavfile.read(filename)

请注意data可能有int数据类型,因此不会在[-1,1]范围内缩放。例如,如果dataint16,则必须将data除以2**15以在[-1,1]范围内进行缩放。

答案 1 :(得分:5)

Sox http://sox.sourceforge.net/可以成为你的朋友。它可以读取许多不同的格式,并以您喜欢的任何数据类型将其输出为raw。实际上,我只是编写代码来将一个数据块从一个音频文件读入一个numpy数组。

我决定采用这种方式实现可移植性(sox可以广泛使用)并最大限度地提高我可以使用的输入音频类型的灵活性。实际上,从最初的测试来看,它似乎并没有明显慢于我正在使用它...这是从很长(小时)的文件读取短(几秒)的音频。

您需要的变量:

SOX_EXEC # the sox / sox.exe executable filename
filename # the audio filename of course
num_channels # duh... the number of channels
out_byps # Bytes per sample you want, must be 1, 2, 4, or 8

start_samp # sample number to start reading at
len_samp   # number of samples to read

实际代码非常简单。如果要提取整个文件,可以删除start_samp,len_samp和'trim'。

import subprocess # need the subprocess module
import numpy as NP # I'm lazy and call numpy NP

cmd = [SOX_EXEC,
       filename,              # input filename
       '-t','raw',            # output file type raw
       '-e','signed-integer', # output encode as signed ints
       '-L',                  # output little endin
       '-b',str(out_byps*8),  # output bytes per sample
       '-',                   # output to stdout
       'trim',str(start_samp)+'s',str(len_samp)+'s'] # only extract requested part 

data = NP.fromstring(subprocess.check_output(cmd),'<i%d'%(out_byps))
data = data.reshape(len(data)/num_channels, num_channels) # make samples x channels

PS:这是使用sox从音频文件头读取内容的代码...

    info = subprocess.check_output([SOX_EXEC,'--i',filename])
    reading_comments_flag = False
    for l in info.splitlines():
        if( not l.strip() ):
            continue
        if( reading_comments_flag and l.strip() ):
            if( comments ):
                comments += '\n'
            comments += l
        else:
            if( l.startswith('Input File') ):
                input_file = l.split(':',1)[1].strip()[1:-1]
            elif( l.startswith('Channels') ):
                num_channels = int(l.split(':',1)[1].strip())
            elif( l.startswith('Sample Rate') ):
                sample_rate = int(l.split(':',1)[1].strip())
            elif( l.startswith('Precision') ):
                bits_per_sample = int(l.split(':',1)[1].strip()[0:-4])
            elif( l.startswith('Duration') ):
                tmp = l.split(':',1)[1].strip()
                tmp = tmp.split('=',1)
                duration_time = tmp[0]
                duration_samples = int(tmp[1].split(None,1)[0])
            elif( l.startswith('Sample Encoding') ):
                encoding = l.split(':',1)[1].strip()
            elif( l.startswith('Comments') ):
                comments = ''
                reading_comments_flag = True
            else:
                if( other ):
                    other += '\n'+l
                else:
                    other = l
                if( output_unhandled ):
                    print >>sys.stderr, "Unhandled:",l
                pass

答案 2 :(得分:4)

FFmpeg支持mp3并适用于Windows(http://zulko.github.io/blog/2013/10/04/read-and-write-audio-files-in-python-using-ffmpeg/)。

读取mp3文件:

import subprocess as sp

FFMPEG_BIN = "ffmpeg.exe"

command = [ FFMPEG_BIN,
        '-i', 'mySong.mp3',
        '-f', 's16le',
        '-acodec', 'pcm_s16le',
        '-ar', '44100', # ouput will have 44100 Hz
        '-ac', '2', # stereo (set to '1' for mono)
        '-']
pipe = sp.Popen(command, stdout=sp.PIPE, bufsize=10**8)

将数据格式化为numpy数组:

raw_audio = pipe.proc.stdout.read(88200*4)

import numpy

audio_array = numpy.fromstring(raw_audio, dtype="int16")
audio_array = audio_array.reshape((len(audio_array)/2,2))

答案 3 :(得分:1)

如果您想为MP3

执行此操作

以下是我使用的内容:它使用pydub和scipy。

完整设置(在Mac上,在其他系统上可能有所不同):

import tempfile
import os
import pydub
import scipy
import scipy.io.wavfile


def read_mp3(file_path, as_float = False):
    """
    Read an MP3 File into numpy data.
    :param file_path: String path to a file
    :param as_float: Cast data to float and normalize to [-1, 1]
    :return: Tuple(rate, data), where
        rate is an integer indicating samples/s
        data is an ndarray(n_samples, 2)[int16] if as_float = False
            otherwise ndarray(n_samples, 2)[float] in range [-1, 1]
    """

    path, ext = os.path.splitext(file_path)
    assert ext=='.mp3'
    mp3 = pydub.AudioSegment.from_mp3(FILEPATH)
    _, path = tempfile.mkstemp()
    mp3.export(path, format="wav")
    rate, data = scipy.io.wavfile.read(path)
    os.remove(path)
    if as_float:
        data = data/(2**15)
    return rate, data

归功于James Thompson's blog

答案 4 :(得分:1)

我最近一直在使用PySoundFile而不是Audiolab。它可以使用conda轻松安装。

does not support mp3,就像大多数事情一样。 MP3不再获得专利,因此没有理由不支持它;有人必须write support into libsndfile