簡體   English   中英

如何在Python中操作wav文件數據?

[英]How to manipulate wav file data in Python?

我正在嘗試讀取一個wav文件,然后操作其內容,逐個樣本

這是我到目前為止所擁有的:

import scipy.io.wavfile
import math

rate, data = scipy.io.wavfile.read('xenencounter_23.wav')

for i in range(len(data)):
    data[i][0] = math.sin(data[i][0])
    print data[i][0]

我得到的結果是:

0
0
0
0
0
0

等等

它讀得正確,因為如果我寫了print data[i]我通常得到大小為2的非零數組。

wavfile.read返回的數組data是一個整數數據類型的numpy數組。 numpy數組的數據類型無法就地更改,因此這一行:

data[i][0] = math.sin(data[i][0])

math.sin的結果math.sin為整數,該整數始終為0。

而不是該行,創建一個新的浮點數組來存儲您的計算結果。

或者使用numpy.sin計算數組中所有元素的正弦值:

import numpy as np
import scipy.io.wavfile

rate, data = scipy.io.wavfile.read('xenencounter_23.wav')

sin_data = np.sin(data)

print sin_data

從您的附加注釋中,您似乎想要獲取每個值的正弦值並將結果寫為新的wav文件。

這是一個(我認為)做你想要的例子。 我將從這里使用文件'M1F1-int16-AFsp.wav': http ://www-mmsp.ece.mcgill.ca/Documents/AudioFormats/WAVE/Samples.html。 show_info函數只是說明每個步驟結果的便捷方式。 如果您使用的是交互式shell,則可以使用它來檢查變量及其屬性。

import numpy as np
from scipy.io import wavfile

def show_info(aname, a):
    print "Array", aname
    print "shape:", a.shape
    print "dtype:", a.dtype
    print "min, max:", a.min(), a.max()
    print

rate, data = wavfile.read('M1F1-int16-AFsp.wav')

show_info("data", data)

# Take the sine of each element in `data`.
# The np.sin function is "vectorized", so there is no need
# for a Python loop here.
sindata = np.sin(data)

show_info("sindata", sindata)

# Scale up the values to 16 bit integer range and round
# the value.
scaled = np.round(32767*sindata)

show_info("scaled", scaled)

# Cast `scaled` to an array with a 16 bit signed integer data type.
newdata = scaled.astype(np.int16)

show_info("newdata", newdata)

# Write the data to 'newname.wav'
wavfile.write('newname.wav', rate, newdata)

這是輸出。 (初始警告意味着文件中可能存在一些scipy.io.wavfile.read無法理解的元數據。)

<snip>/scipy/io/wavfile.py:147: WavFileWarning: Chunk (non-data) not understood, skipping it.
  WavFileWarning)
Array 'data'
shape: (23493, 2)
dtype: int16
min, max: -7125 14325

Array 'sindata'
shape: (23493, 2)
dtype: float32
min, max: -0.999992 0.999991

Array 'scaled'
shape: (23493, 2)
dtype: float32
min, max: -32767.0 32767.0

Array 'newdata'
shape: (23493, 2)
dtype: int16
min, max: -32767 32767

新文件'newname.wav'包含兩個帶符號16位值的通道。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM