简体   繁体   中英

How do I take user input "n = str(input("Give str"))" while having the numpy module imported?

my problem is that I can't take input from user ("n = str(input("Give str"))") while having the numpy module imported. I'm new to basically everything in Python and can't get past this problem.

No matter what I do,

"TypeError: 'numpy.ndarray' object is not callable".

The borrowed code I am working with:

import pyaudio
import numpy as np

noteslist = {"C":-10,"C#":-9,"D":-8,"D#":-7,"E":-6,"E#":-5,"F":-4,"F#":-3,"G":-2,"G#":-1,"A":0,"A#":1,"B":2}

n = input("Give") 

fs = 44100       
duration = 5.0  
f = 432.0        

#Until this point I need to be albe to code as if no modules (numpy) have been imported.
#Part 2 of the code

input = np.sin(2*np.pi*np.arange(fs*duration)*f/fs)

def play(input):
    sample = (input).astype(np.float32)
    volume = 0.25
    p = pyaudio.PyAudio()
    stream = p.open(format=pyaudio.paFloat32, channels=1, rate=fs, output=True)
    stream.write(volume*sample)
    stream.stop_stream()
    stream.close()
    p.terminate()

play(input)

Ideas on how to overcome this problem although I have no idea how to realise them:

  1. Make the code create another file or something and paste second half of the code, since the second half is only responsible for playing generated sound (sin).
  2. Split the code into some kind of sections: one without numpy imported, another with numpy imported.
  3. Make the numpy import in the second half of the code, like time.sleep -> import numpy

Thanks so much!

input is a built-in function in python.
Reference: https://docs.python.org/3/library/functions.html#input

You are currently using it as a variable for your numpy array.
This will not work.

Instead rename it to another variable.

Consider this updated code.

import pyaudio
import numpy as np

noteslist = {
    "C": -10,
    "C#": -9,
    "D": -8,
    "D#": -7,
    "E": -6,
    "E#": -5,
    "F": -4,
    "F#": -3,
    "G": -2,
    "G#": -1,
    "A": 0,
    "A#": 1,
    "B": 2,
}

n = input("Give")

fs = 44100
duration = 5.0
f = 432.0

A = np.sin(2 * np.pi * np.arange(fs * duration) * f / fs)

def play(A):
    sample = (A).astype(np.float32)
    volume = 0.25
    p = pyaudio.PyAudio()
    stream = p.open(format=pyaudio.paFloat32, channels=1, rate=fs, output=True)
    stream.write(volume * sample)
    stream.stop_stream()
    stream.close()
    p.terminate()


play(A)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM