Python에서 * .wav 파일 읽기
.wav 파일로 작성된 사운드를 분석해야합니다. 이를 위해이 파일을 숫자 세트 (예 : 배열)로 변환해야합니다. 웨이브 패키지를 사용해야한다고 생각합니다. 그러나 정확히 어떻게 작동하는지 모르겠습니다. 예를 들어 다음을 수행했습니다.
import wave
w = wave.open('/usr/share/sounds/ekiga/voicemail.wav', 'r')
for i in range(w.getnframes()):
frame = w.readframes(i)
print frame
이 코드의 결과로 나는 음압을 시간의 함수로 볼 것으로 예상했습니다. 대조적으로 나는 이상하고 신비한 기호 (16 진수가 아닌)를 많이 본다. 누구든지 저를 도와 줄 수 있습니까?
당 소스 , scipy.io.wavfile.read(somefile)
두 항목 튜플 결과 : 처음 초당 샘플의 샘플링 레이트이고, 두 번째는 인 numpy
데이터 파일로부터 판독 된 모든 어레이와. 사용하기 매우 쉽습니다!
예 :
from scipy.io import wavfile
fs, data = wavfile.read('./output/audio.wav')
나는 오늘 저녁에 약간의 조사를했고 이것을 알아 냈다.
import wave, struct
waveFile = wave.open('sine.wav', 'r')
length = waveFile.getnframes()
for i in range(0,length):
waveData = waveFile.readframes(1)
data = struct.unpack("<h", waveData)
print(int(data[0]))
이 스 니펫이 누군가에게 도움이되기를 바랍니다. 세부 정보 : struct 모듈을 사용하여 웨이브 프레임을 가져올 수 있습니다 (-32768, 0x8000 및 32767, 0x7FFF 사이의 2 초 보완 바이너리). 이것은 MONO, 16-BIT, WAVE 파일을 읽습니다. 나는 이 웹 페이지가 이것을 공식화하는데 매우 유용하다는 것을 알았다 .
이 스 니펫은 1 프레임을 읽습니다. 두 개 이상의 프레임 (예 : 13)을 읽으려면
waveData = waveFile.readframes(13)
data = struct.unpack("<13h", waveData)
wav를 읽을 다른 파이썬 모듈 :
웨이브 오디오 파일을 읽기위한 최소한 다음 라이브러리가 있습니다.
- PySoundFile
- scipy.io.wavfile ( scipy에서 )
- wave (스트림 읽기. Python 2 및 3에 포함됨)
- scikits.audiolab (유지 관리되지 않는 것 같음 )
- 사운드 장치 (사운드 재생 및 녹음, 스트림 및 실시간에 적합)
- 피글렛
가장 간단한 예 :
다음은 Pysoundfile의 간단한 예입니다.
import soundfile as sf
data, samplerate = sf.read('existing_file.wav')
출력 형식 :
경고, 데이터는 라이브러리에 따라 항상 동일한 형식이 아닙니다. 예를 들면 :
from scikits import audiolab
from scipy.io import wavfile
from sys import argv
for filetest in argv[1:]:
[x, fs, nbBits] = audiolab.wavread(filePath)
print '\nReading with scikits.audiolab.wavread: ', x
[fs, x] = wavfile.read(filetest)
print '\nReading with scipy.io.wavfile.read: ', x
scikits.audiolab.wavread로 읽기 : [0. 0. 0. ..., -0.00097656 -0.00079346 -0.00097656] scipy.io.wavfile.read로 읽기 : [0 0 ..., -32 -26 -32 ]
PySoundFile 및 Audiolab은 -1과 1 사이의 float를 반환합니다 (matab이 수행하는 것처럼 오디오 신호에 대한 규칙). Scipy 및 wave는 인코딩 비트 수에 따라 float로 변환 할 수있는 정수를 반환합니다.
예를 들면 :
from scipy.io.wavfile import read as wavread
[samplerate, x] = wavread(audiofilename) # x is a numpy array of integer, representing the samples
# scale to -1.0 -- 1.0
if x.dtype == 'int16':
nb_bits = 16 # -> 16-bit wav files
elif x.dtype == 'int32':
nb_bits = 32 # -> 32-bit wav files
max_nb_bit = float(2 ** (nb_bits - 1))
samples = x / (max_nb_bit + 1.0) # samples is a numpy array of float representing the samples
IMHO, 사운드 파일의 오디오 데이터를 NumPy 배열로 가져 오는 가장 쉬운 방법은 PySoundFile입니다 .
import soundfile as sf
data, fs = sf.read('/usr/share/sounds/ekiga/voicemail.wav')
이것은 또한 24 비트 파일을 즉시 지원합니다.
많은 사운드 파일 라이브러리를 사용할 수 있으며 몇 가지 장단점을 볼 수 있는 개요를 작성 했습니다 . 또한 모듈을 사용하여 24 비트 wav 파일을 읽는 방법을wave
설명 하는 페이지도 있습니다 .
scikits.audiolab 모듈을 사용하여이를 수행 할 수 있습니다 . 작동하려면 NumPy 및 SciPy와 libsndfile이 필요합니다.
참고로 OSX가 아닌 Ubunutu에서만 작동하도록 할 수있었습니다.
from scikits.audiolab import wavread
filename = "testfile.wav"
data, sample_frequency,encoding = wavread(filename)
이제 wav 데이터가 있습니다.
블록 단위로 오디오를 처리하려는 경우 주어진 솔루션 중 일부는 전체 오디오를 메모리에로드하여 많은 캐시 미스를 생성하고 프로그램 속도를 느리게한다는 점에서 상당히 끔찍합니다. python-wavefile 은 생성기를 통해 효율적이고 투명한 블록 관리를 사용하여 NumPy 블록 별 처리를 수행하는 몇 가지 파이썬 구조를 제공합니다. 다른 파이썬적인 장점은 파일에 대한 컨텍스트 관리자, 속성으로서의 메타 데이터 ... 그리고 전체 파일 인터페이스를 원한다면 빠른 프로토 타입을 개발하고 효율성에 신경 쓰지 않기 때문에 전체 파일 인터페이스가 여전히 존재합니다.
처리의 간단한 예는 다음과 같습니다.
import sys
from wavefile import WaveReader, WaveWriter
with WaveReader(sys.argv[1]) as r :
with WaveWriter(
'output.wav',
channels=r.channels,
samplerate=r.samplerate,
) as w :
# Just to set the metadata
w.metadata.title = r.metadata.title + " II"
w.metadata.artist = r.metadata.artist
# This is the prodessing loop
for data in r.read_iter(size=512) :
data[1] *= .8 # lower volume on the second channel
w.write(data)
The example reuses the same block to read the whole file, even in the case of the last block that usually is less than the required size. In this case you get an slice of the block. So trust the returned block length instead of using a hardcoded 512 size for any further processing.
If you're going to perform transfers on the waveform data then perhaps you should use SciPy, specifically scipy.io.wavfile
.
I needed to read a 1-channel 24-bit WAV file. The post above by Nak was very useful. However, as mentioned above by basj 24-bit is not straightforward. I finally got it working using the following snippet:
from scipy.io import wavfile
TheFile = 'example24bit1channelFile.wav'
[fs, x] = wavfile.read(TheFile)
# convert the loaded data into a 24bit signal
nx = len(x)
ny = nx/3*4 # four 3-byte samples are contained in three int32 words
y = np.zeros((ny,), dtype=np.int32) # initialise array
# build the data left aligned in order to keep the sign bit operational.
# result will be factor 256 too high
y[0:ny:4] = ((x[0:nx:3] & 0x000000FF) << 8) | \
((x[0:nx:3] & 0x0000FF00) << 8) | ((x[0:nx:3] & 0x00FF0000) << 8)
y[1:ny:4] = ((x[0:nx:3] & 0xFF000000) >> 16) | \
((x[1:nx:3] & 0x000000FF) << 16) | ((x[1:nx:3] & 0x0000FF00) << 16)
y[2:ny:4] = ((x[1:nx:3] & 0x00FF0000) >> 8) | \
((x[1:nx:3] & 0xFF000000) >> 8) | ((x[2:nx:3] & 0x000000FF) << 24)
y[3:ny:4] = (x[2:nx:3] & 0x0000FF00) | \
(x[2:nx:3] & 0x00FF0000) | (x[2:nx:3] & 0xFF000000)
y = y/256 # correct for building 24 bit data left aligned in 32bit words
Some additional scaling is required if you need results between -1 and +1. Maybe some of you out there might find this useful
if its just two files and the sample rate is significantly high, you could just interleave them.
from scipy.io import wavfile
rate1,dat1 = wavfile.read(File1)
rate2,dat2 = wavfile.read(File2)
if len(dat2) > len(dat1):#swap shortest
temp = dat2
dat2 = dat1
dat1 = temp
output = dat1
for i in range(len(dat2)/2): output[i*2]=dat2[i*2]
wavfile.write(OUTPUT,rate,dat)
u can also use simple import wavio
library u also need have some basic knowledge of the sound.
참고URL : https://stackoverflow.com/questions/2060628/reading-wav-files-in-python
'Program Tip' 카테고리의 다른 글
범위 입력 슬라이더를 세로로 표시하는 방법 (0) | 2020.10.20 |
---|---|
R의 대체 문자를 기반으로 문자열 분할 (0) | 2020.10.20 |
Capybara에서 "_blank"대상이있는 링크의 새 창으로 어떻게 전환합니까? (0) | 2020.10.20 |
Visual Studio : 솔루션 탐색기를 현재 파일로 스크롤하는 바로 가기 (0) | 2020.10.20 |
UITableView 구분선 (0) | 2020.10.20 |