user21063
user21063

Reputation: 143

Why is int type error? TypeError

I got an error, TypeError: slice indices must be integers or None or have an index method . Traceback is like

Traceback (most recent call last):
  File "test.py", line 24, in <module>
    wavdata = wav[z:q]
TypeError: slice indices must be integers or None or have an __index__ method

My code is

#coding:utf-8
import wave
import numpy as np
from pylab import *

def wavread(filename):
    wf = wave.open(filename, "r")
    fs = wf.getframerate()
    x = wf.readframes(wf.getnframes())
    x = np.frombuffer(x, dtype="int16") / 32768.0  # (-1, 1)に正規化
    wf.close()
    return x, float(fs)

if __name__ == "__main__":
    wav, fs = wavread("3_7_9.wav")
    t = np.arange(0.0, len(wav) / fs, 1/fs)

    center = len(wav) // 2  
    cuttime = 0.04         
    z = center-cuttime // 2*fs
    q= center + cuttime // 2*fs
    wavdata = wav[z:q]
    time = t[z:q]

    plot(time * 1000, wavdata)
    xlabel("time [ms]")
    ylabel("amplitude")
    savefig("waveform.png")
    show()

I think variable of center & z & q is int type, so I really cannot understand why this error happen.First,I wrote this part like

if __name__ == "__main__":
    wav, fs = wavread("3_7_9.wav")
    t = np.arange(0.0, len(wav) / fs, 1/fs)

    center = len(wav) / 2  
    cuttime = 0.04         
    z = center-cuttime / 2*fs
    q= center + cuttime / 2*fs
    wavdata = wav[z:q]
    time = t[z:q]

    plot(time * 1000, wavdata)
    xlabel("time [ms]")
    ylabel("amplitude")
    savefig("waveform.png")
    show()

so these division parts are not int type but float type,therefore I could understand why this error happen.But now I changed these part into //,so these parts is int.So,how can I fix this error?

Upvotes: 1

Views: 109

Answers (2)

Shreyash S Sarnayak
Shreyash S Sarnayak

Reputation: 2335

The variable z and q are still float

center = len(wav) // 2  
cuttime = 0.04         
z = center - cuttime // 2 * fs
q = center + cuttime // 2 * fs

Because both cuttime and fs are float, so the whole expression becomes float.

You need to cast it to int like

z = int(center - cuttime // 2 * fs)
q = int(center + cuttime // 2 * fs)

Upvotes: 2

mic4ael
mic4ael

Reputation: 8290

Probably, the problem stems from the fact that your variables z and q are floats. Make sure you cast them to int.

Upvotes: 1

Related Questions