ali
ali

Reputation: 119

Reading wav files in a folder with Python

Here is my code :

for filename in glob.glob('*.wav') : 
    for i in range(10) : 
        sr[i],x[i]=scipy.io.wavfile.read(filename)

I want to read .wav files in a folder and save their values on x and also their sampling rates on sr. But my code gives error: "list assignment index out of range". How can I fix it? I am using python2.7 on ubuntu.

Upvotes: 1

Views: 1309

Answers (1)

RichSmith
RichSmith

Reputation: 940

I could be wrong but I'm guessing it'll be the line:

sr[i],x[i] = scipy.io.wavfile.read(filename)

I don't think you'll be able to index the results like that as I dont think they're lists.

try this instead:

sr, x = scipy.io.wavfile.read(filename)

If you need a list of the sr and x values, try defining the lists before reading the files. Append the results individually to each of your lists. There is probably a clever way of writing this, but for clarity I'll just do it like this:

sr = []
x = []

for filename in glob.glob('*.wav'):
    for i in range(10):
        sr_value, x_value = scipy.io.wavfile.read(filename)
        sr.append(sr_value)
        x.append(x_value)

I'd also maybe recommend renaming your sr and x (particularly x) variables to something more meaningful. It might make your code a bit easier to read and it could save you a few naming conflicts later down the line.

Upvotes: 2

Related Questions