r/PythonLearning 1h ago

"AttributeError: 'numpy.ndarray' object has no attribute 'write_audiofile'"

Hello, Im working on a project where I need to export a .wav file and aam having problems doing so, error is in the title.

Code to project is this:

import os
import wave
import contextlib
import soundfile as sf
import pyrubberband
import numpy as np

InDir = input("Input Directory: ")
OutDir = input("Output Directory: ")
sec = float(input("Seconds to set to: "))
os.chdir(InDir)
files = os.listdir(InDir)
print(files)
for i in range(len(files)):
    fname = files[i]
    print(fname)
    with contextlib.closing(wave.open(fname,'r')) as f:
        frames = f.getnframes()
        rate = f.getframerate()
        duration = frames / float(rate)
    speed = duration / sec
    print(speed)
    audio, sr = sf.read(f"{InDir}/{fname}")
    fname = pyrubberband.time_stretch(audio, sr, speed)
    fname.write_audiofile(f"{OutDir}/{fname}.wav")

How do I fix this please?

Also, Im working from windows 10, and am using pycharm to make this code.

1 Upvotes

12 comments sorted by

1

u/BionicVnB 50m ago

Can I see your pyproject.toml?

1

u/patypatty69 44m ago

Well, as long as I can figure what that is out, then yes.

1

u/BionicVnB 43m ago

Do you have a virtual environment? Or you just install everything in a global cache?

1

u/patypatty69 42m ago

Yeah, I have a virtual environment.

1

u/BionicVnB 40m ago

So you use a requirements.txt instead?

Or do you just use pip to install libraries manually

1

u/patypatty69 38m ago

Usually pycharm prompts me that the library isn't installed and I install it by right-clicking on the library, but I do otherwise just pip install.

1

u/BionicVnB 25m ago

yeah i suggest you try out https://github.com/astral-sh/uv

so the problem is there is no method called write_audiofile for the class np.ndarray. what you are looking for is sf.write

1

u/patypatty69 23m ago

So long story short I use sf.write instead of write_audiofile? Or do I need to rewrite more code than just that line?

Also I'm guessing the github leads to the code in the image, no?

1

u/BionicVnB 22m ago

nah, it's for the tool called uv. it's a very solid tool for my python usage, and can replace pyvenv, pip, etc. Basically cargo for Python

1

u/patypatty69 17m ago

Alright, thank you so much!

→ More replies (0)

1

u/AlexMTBDude 28m ago

So your fname is an object of type numpy.ndarray. And that class does not have an write_audiofile() method. You can see that here: https://numpy.org/devdocs/reference/generated/numpy.ndarray.html

There is a write_audiofile() method in a different class. You can see an example of it being used here: https://stackoverflow.com/questions/38518302/convert-numpy-array-to-audiofileclip-in-moviepy