Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/323.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 错误:未知格式:3(尝试读取音频文件时)_Python_Audio_Wav_Data Cleaning_Downsampling - Fatal编程技术网

Python 错误:未知格式:3(尝试读取音频文件时)

Python 错误:未知格式:3(尝试读取音频文件时),python,audio,wav,data-cleaning,downsampling,Python,Audio,Wav,Data Cleaning,Downsampling,我正在尝试使用下面显示的以下功能清理和减少音频采样。我陷入了这个我不理解的错误中。有人愿意解释一下,希望能帮我解决这个问题吗 我可以看到,这与wavio函数有关,它无法读取文件 代码如下: def envelope(y, rate, threshold): mask = [] y = pd.Series(y).apply(np.abs) y_mean = y.rolling(window=int(rate/20), min_p

我正在尝试使用下面显示的以下功能清理和减少音频采样。我陷入了这个我不理解的错误中。有人愿意解释一下,希望能帮我解决这个问题吗

我可以看到,这与wavio函数有关,它无法读取文件

代码如下:

def envelope(y, rate, threshold):
    mask = []
    y = pd.Series(y).apply(np.abs)
    y_mean = y.rolling(window=int(rate/20),
                       min_periods=1,
                       center=True).max()
    for mean in y_mean:
        if mean > threshold:
            mask.append(True)
        else:
            mask.append(False)
    return mask, y_mean


def downsample_mono(path, sr):
    obj = wavio.read(path)
    wav = obj.data.astype(np.float32, order='F')
    rate = obj.rate
    try:
        tmp = wav.shape[1]
        wav = to_mono(wav.T)
    except:
        pass
    wav = resample(wav, rate, sr)
    wav = wav.astype(np.int16)
    return sr, wav


def save_sample(sample, rate, target_dir, fn, ix):
    fn = fn.split('.wav')[0]
    dst_path = os.path.join(target_dir.split('.')[0], fn+'_{}.wav'.format(str(ix)))
    if os.path.exists(dst_path):
        return
    wavfile.write(dst_path, rate, sample)


def check_dir(path):
    if os.path.exists(path) is False:
        os.mkdir(path)


def split_wavs(args):
    src_root = args.src_root
    dst_root = args.dst_root
    dt = args.delta_time

    wav_paths = glob('{}/**'.format(src_root), recursive=True)
    wav_paths = [x for x in wav_paths if '.wav' in x]
    dirs = os.listdir(src_root)
    check_dir(dst_root)
    classes = os.listdir(src_root)
    for _cls in classes:
        target_dir = os.path.join(dst_root, _cls)
        check_dir(target_dir)
        src_dir = os.path.join(src_root, _cls)
        for fn in tqdm(os.listdir(src_dir)):
            src_fn = os.path.join(src_dir, fn)
            rate, wav = downsample_mono(src_fn, args.sr)
            mask, y_mean = envelope(wav, rate, threshold=args.threshold)
            wav = wav[mask]
            delta_sample = int(dt*rate)

            # cleaned audio is less than a single sample
            # pad with zeros to delta_sample size
            if wav.shape[0] < delta_sample:
                sample = np.zeros(shape=(delta_sample,), dtype=np.int16)
                sample[:wav.shape[0]] = wav
                save_sample(sample, rate, target_dir, fn, 0)
            # step through audio and save every delta_sample
            # discard the ending audio if it is too short
            else:
                trunc = wav.shape[0] % delta_sample
                for cnt, i in enumerate(np.arange(0, wav.shape[0]-trunc, delta_sample)):
                    start = int(i)
                    stop = int(i + delta_sample)
                    sample = wav[start:stop]
                    save_sample(sample, rate, target_dir, fn, cnt)


def test_threshold(args):
    src_root = args.src_root
    wav_paths = glob('{}/**'.format(src_root), recursive=True)
    wav_path = [x for x in wav_paths if args.fn in x]
    if len(wav_path) != 1:
        print('audio file not found for sub-string: {}'.format(args.fn))
        return
    rate, wav = downsample_mono(wav_path[0], args.sr)
    mask, env = envelope(wav, rate, threshold=args.threshold)
    plt.style.use('ggplot')
    plt.title('Signal Envelope, Threshold = {}'.format(str(args.threshold)))
    plt.plot(wav[np.logical_not(mask)], color='r', label='remove')
    plt.plot(wav[mask], color='c', label='keep')
    plt.plot(env, color='m', label='envelope')
    plt.grid(False)
    plt.legend(loc='best')
    plt.show()

if __name__ == '__main__':

    parser = argparse.ArgumentParser(description='Cleaning audio data')
    parser.add_argument('--src_root', type=str, default='Audio Data/Ordered Files',
                        help='directory of audio files in total duration')
    parser.add_argument('--dst_root', type=str, default='Audio Data/Clean Audio',
                        help='directory to put audio files split by delta_time')
    parser.add_argument('--delta_time', '-dt', type=float, default=2.0,
                        help='time in seconds to sample audio')
    parser.add_argument('--sr', type=int, default=44100,
                        help='rate to downsample audio')

    parser.add_argument('--fn', type=str, default='HBJQWAO',
                        help='file to plot over time to check magnitude')
    parser.add_argument('--threshold', type=str, default=20,
                        help='threshold magnitude for np.int16 dtype')
    args, _ = parser.parse_known_args()

    test_threshold(args)
    #split_wavs(args)
def信封(y、速率、阈值):
掩码=[]
y=pd系列(y).应用(np.abs)
y_平均值=y.滚动(窗口=整数(比率/20),
最小周期=1,
中心=真)。最大值()
对于y_平均值中的平均值:
如果平均值>阈值:
mask.append(True)
其他:
mask.append(False)
返回面具,你是说
def下采样单声道(路径,sr):
obj=波形读取(路径)
wav=obj.data.astype(np.float32,order='F')
比率=目标比率
尝试:
tmp=波形[1]
wav=至单声道(wav.T)
除:
通过
wav=重采样(wav、速率、sr)
wav=wav.astype(np.int16)
返回sr,wav
def保存样本(样本、速率、目标目录、fn、ix):
fn=fn.split('.wav')[0]
dst_path=os.path.join(target_dir.split('.')[0],fn+''{}.wav'.格式(str(ix)))
如果os.path.存在(dst_路径):
返回
wavfile.write(dst_路径、速率、样本)
def check_dir(路径):
如果os.path.exists(path)为False:
os.mkdir(路径)
def分割波形(参数):
src_root=args.src_root
dst_根=args.dst_根
dt=args.delta_时间
wav_path=glob('{}/**'.format(src_root),recursive=True)
wav_路径=[x表示x在wav_路径中,如果x中的“.wav”]
dirs=os.listdir(src_根)
检查目录(dst根目录)
classes=os.listdir(src\u根)
对于类中的_cls:
target_dir=os.path.join(dst_root,_cls)
检查目录(目标目录)
src\u dir=os.path.join(src\u root,\u cls)
对于tqdm中的fn(os.listdir(src_dir)):
src\u fn=os.path.join(src\u dir,fn)
速率,wav=下采样单声道(src\u fn,args.sr)
掩码,y_平均值=包络(波形、速率、阈值=参数阈值)
wav=wav[遮罩]
delta_样本=int(dt*速率)
#清理后的音频少于一个样本
#用0填充到delta_样本大小
如果波形[0]
错误:

Error                                     Traceback (most recent call last)
<ipython-input-16-97e9b68095c0> in <module>()
     17     args, _ = parser.parse_known_args()
     18 
---> 19     test_threshold(args)
     20     #split_wavs(args)

6 frames
<ipython-input-14-fe4eeabe5e06> in test_threshold(args)
     85         print('audio file not found for sub-string: {}'.format(args.fn))
     86         return
---> 87     rate, wav = downsample_mono(wav_path[0], args.sr)
     88     mask, env = envelope(wav, rate, threshold=args.threshold)
     89     plt.style.use('ggplot')

<ipython-input-14-fe4eeabe5e06> in downsample_mono(path, sr)
     14 
     15 def downsample_mono(path, sr):
---> 16     obj = wavio.read(path)
     17     wav = obj.data.astype(np.float32, order='F')
     18     rate = obj.rate

/usr/local/lib/python3.6/dist-packages/wavio.py in read(file)
    166     with values that have been sign-extended.
    167     """
--> 168     wav = _wave.open(file)
    169     rate = wav.getframerate()
    170     nchannels = wav.getnchannels()

/usr/lib/python3.6/wave.py in open(f, mode)
    497             mode = 'rb'
    498     if mode in ('r', 'rb'):
--> 499         return Wave_read(f)
    500     elif mode in ('w', 'wb'):
    501         return Wave_write(f)

/usr/lib/python3.6/wave.py in __init__(self, f)
    161         # else, assume it is an open file object already
    162         try:
--> 163             self.initfp(f)
    164         except:
    165             if self._i_opened_the_file:

/usr/lib/python3.6/wave.py in initfp(self, file)
    141             chunkname = chunk.getname()
    142             if chunkname == b'fmt ':
--> 143                 self._read_fmt_chunk(chunk)
    144                 self._fmt_chunk_read = 1
    145             elif chunkname == b'data':

/usr/lib/python3.6/wave.py in _read_fmt_chunk(self, chunk)
    258             self._sampwidth = (sampwidth + 7) // 8
    259         else:
--> 260             raise Error('unknown format: %r' % (wFormatTag,))
    261         self._framesize = self._nchannels * self._sampwidth
    262         self._comptype = 'NONE'

Error: unknown format: 3
错误回溯(最近一次调用上次)
在()
17个参数,u=parser.parse_known_args()
18
--->19测试阈值(args)
20#分割波(args)
6帧
测试中_阈值(args)
85打印('未找到子字符串{}的音频文件。格式(args.fn))
86返回
--->87速率,wav=downsample\u mono(wav\u路径[0],args.sr)
88掩码,环境=包络(波形,速率,阈值=参数阈值)
89 plt.style.use('ggplot'))
在下采样单声道中(路径,sr)
14
15 def下采样单声道(路径,sr):
--->16 obj=波形读取(路径)
17 wav=obj.data.astype(np.float32,order='F')
18费率=目标费率
/读取(文件)中的usr/local/lib/python3.6/dist-packages/wavio.py
166,具有已符号扩展的值。
167     """
-->168 wav=_wave.open(文件)
169速率=wav.getframerate()
170 nchannels=wav.getnchannels()
/usr/lib/python3.6/wave.py处于打开状态(f模式)
497模式='rb'
498“r”、“rb”中的if模式:
-->499返回波读取(f)
“w”、“wb”中的500 elif模式:
501返回波写入(f)
/usr/lib/python3.6/wave.py in_uuuuinit_uuu(self,f)
161#其他,assu
import soundfile as sf
data, samplerate = sf.read('file.wav', dtype='float32')