错误:未知格式:3尝试读取音频wavfile时

如何解决错误:未知格式:3尝试读取音频wavfile时

我正在尝试使用下面显示的以下功能清除音频并对其进行降采样。我陷入了我不了解的错误。有人愿意解释并希望能帮助我解决此问题吗?

我看到它与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,sr)
    wav = wav.astype(np.int16)
    return sr,wav


def save_sample(sample,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,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,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,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,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,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',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',default='HBJQWAO',help='file to plot over time to check magnitude')
    parser.add_argument('--threshold',default=20,help='threshold magnitude for np.int16 dtype')
    args,_ = parser.parse_known_args()

    test_threshold(args)
    #split_wavs(args)

错误:

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,args.sr)
     88     mask,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

解决方法

用例如soxi,您会发现WAVE不是以int16格式编写的,而是float编写的。我怎么知道This code读取wFormatTag标签。在您的情况下,异常返回的代码为3reference),FLOAT

一种选择是使用pySoundFile并指定float作为数据格式。

import soundfile as sf
data,samplerate = sf.read('file.wav',dtype='float32')

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-