python-3.xnumpylinspace

Using numpy.linspace() method for a simpleaudio project, I get a typeError when I change the duration to a float. How do I work around this problem?


"""Here is the exact code from the simpleaudio docs which produces the error TypeError: object of type cannot be safely interpreted as an integer. The problem is T = 0.25. Everything works fine as long as T is an integer, however I require the ability to work with T as a decimal. """

import numpy as np
import simpleaudio as sa

# calculate note frequencies
A_freq = 440
Csh_freq = A_freq * 2 ** (4 / 12)
E_freq = A_freq * 2 ** (7 / 12)

# get timesteps for each sample, T is note duration in seconds
sample_rate = 44100
T = 0.25
t = np.linspace(0, T, T * sample_rate, False)

# generate sine wave notes
A_note = np.sin(A_freq * t * 2 * np.pi)
Csh_note = np.sin(Csh_freq * t * 2 * np.pi)
E_note = np.sin(E_freq * t * 2 * np.pi)

# concatenate notes
audio = np.hstack((A_note, Csh_note, E_note))
# normalize to 16-bit range
audio *= 32767 / np.max(np.abs(audio))
# convert to 16-bit data
audio = audio.astype(np.int16)

# start playback
play_obj = sa.play_buffer(audio, 1, 2, sample_rate)

# wait for playback to finish before exiting
play_obj.wait_done()

Solution

  • The problem doesn't really come from T itself actually, but from T * sample_rate. linspace divides the space between its first and second argument into n + 1 parts (or equivalently, n points), where n is its third argument. Even though T * sample_rate is a whole number mathematically speaking, it is a float the way you compute it. Hence, to get your code working, you just have to cast it to an int:

    sample_rate = 44100
    T = 0.25
    t = np.linspace(0, T, int(T * sample_rate), False)