numpy 有没有办法在不声明持续时间的情况下播放声音?

hmmo2u0o  于 11个月前  发布在  其他
关注(0)|答案(1)|浏览(82)

我有一个代码,它基本上产生一个波(正弦,三角形,.),但只有一定的持续时间。我也有midi实现,当我按下一个按钮的声音开始产生(和播放)。有没有什么解决方案,以停止声音时,我unpress按钮?我试图删除从np的持续时间。安排,但它没有帮助

import time
from rtmidi.midiutil import open_midiinput
import numpy as np
import pyaudio

p = pyaudio.PyAudio()
play = True

volume = 0.5  # range [0.0, 1.0]
fs = 44100  # sampling rate, Hz, must be integer
duration = 5.0  # in seconds, may be float
fA = 440.0  # sine frequency, Hz, may be float
fB = 493.88
fC = 523.25
fD = 587.33

frekvence = 440

frekvence_seznam = {
    (144, 32): fA,
    (144, 33): fB,
    (144, 34): fC,
    (144, 35): fD,

}

port = 0

midiin, port_name = open_midiinput(port)

while True:
    msg = midiin.get_message()

    if msg:
        # klic = tuple(vstupni_list[:2])
        message = msg
        klic = message[0]
        lepsi_klic = tuple(klic[:2])
        print(message[0])

        if lepsi_klic in frekvence_seznam:
            print("je to tam")
            frekvence = frekvence_seznam[lepsi_klic]

            period = 2 * np.pi
            x = period * np.arange(fs * duration) * frekvence / fs

            sinus = np.sin(x)
            square = np.sign(sinus)
            triangle = 2/np.pi * np.arcsin(np.sin(x))
            saw = abs((x % period) - 1)
            curvy_triangle = (abs((x % period) - 1)) ** 2

            samples = (triangle).astype(np.float32)

            # for paFloat32 sample values must be in range [-1.0, 1.0]
            stream = p.open(format=pyaudio.paFloat32,
                            channels=1,
                            rate=fs,
                            output=True)

            vysledek = volume * samples

            # spusteni zvuku

            while play == True:
                start_time = time.time()
                stream.write(vysledek)
                time.sleep(1)
                play = False

                stream.stop_stream()
            play = True
        elif lepsi_klic == (144, 81):
            exit()
stream.close()

p.terminate()
# exit()

字符串

ryoqjall

ryoqjall1#

while play == True:
    start_time = time.time()
    stream.write(vysledek)
    time.sleep(1)
    play = False

字符串
程序的这一部分将开始循环,但在第一次循环结束时停止循环。你试过不这样做吗?
删除这些行:time.sleep(1)play = False
stream.stop_stream()移出while循环。
然后看看你是否能接受这个结果。一旦声音永远循环,你就可以专注于让它再次停止。

相关问题