如何将 .pcm 文件转换为 .wav 文件(脚本) [英] How to convert .pcm files to .wav files (scripting)

查看:39
本文介绍了如何将 .pcm 文件转换为 .wav 文件(脚本)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 Python 脚本中使用 SOX 等工具将 .pcm 文件转换为 .wav 文件.该工具需要跨平台兼容(Windows 和 Linux).有什么建议吗?

I would like to convert .pcm files to .wav files using a tool such as SOX in a Python script. The tool needs to be cross platform compatible (Windows & Linux). Any suggestions?

推荐答案

您实际上不需要为此使用工具.Python 标准库带有 wave 模块,用于编写 .wav 文件,当然原始 .pcm 文件可以作为纯二进制文件打开,如果您需要进行任何简单的转换,这些转换对于列表理解来说不是微不足道的,它们对于 audioop.

You don't actually need a tool for this. The Python standard library comes with the wave module for writing .wav files, and of course raw .pcm files can be just opened as plain binary files, and if you need to do any simple transformations that aren't trivial with a list comprehension, they're trivial with audioop.

例如,这是一个将立体声 16 位 little-endian 44.1k PCM 文件转换为 WAV 文件的完整程序:

For example, this is a complete program from converting stereo 16-bit little-endian 44.1k PCM files to WAV files:

import sys
import wave

for arg in sys.argv[1:]:
    with open(arg, 'rb') as pcmfile:
        pcmdata = pcmfile.read()
    with wave.open(arg+'.wav', 'wb') as wavfile:
        wavfile.setparams((2, 2, 44100, 0, 'NONE', 'NONE'))
        wavfile.writeframes(pcmdata)

在旧版本的 Python 中,您可能必须使用 with contextlib.closure(wave.open(…))(或显式的 openclose 而不是 with 语句).

In older versions of Python, you may have to use with contextlib.closing(wave.open(…)) (or an explicit open and close instead of a with statement).

这篇关于如何将 .pcm 文件转换为 .wav 文件(脚本)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆