PyAudio:播放声音不止一次

时间:2018-09-13 16:18:49

标签: pyaudio

我是Python和Kivy的新手,我的应用程序需要一些帮助。 我正在使用PyAudio播放声音,每次想对其进行一些修改(例如,更改声音的强度)时,都会使用键盘箭头。如果我仅加载一种声音(.wav文件),则此方法非常有效。如果要加载更多文件(一个接一个),则必须按键盘上的一个键,否则它不会加载声音。就我而言,我需要在第一个声音结束后自动加载.wav文件。谁能帮我这个?预先谢谢你。

请在下面找到相关代码:

class MyKeyboardListener(Widget):

def __init__(self, **kwargs):
    super(MyKeyboardListener, self).__init__(**kwargs)
    self._keyboard = Window.request_keyboard(
        self._keyboard_closed, self, 'text')
    if self._keyboard.widget:
    # If it exists, this widget is a VKeyboard object which you can use
    # to change the keyboard layout.
        pass
    self._keyboard.bind(on_key_down=self._on_keyboard_down)


def _keyboard_closed(self):
    print('My keyboard have been closed!')
    self._keyboard.unbind(on_key_down=self._on_keyboard_down)
    self._keyboard = None


def _on_keyboard_down(self, keyboard, keycode, text, modifiers):
    print('The key', keycode, 'have been pressed')
    print(' - text is %r' % text)
    print(' - modifiers are %r' % modifiers)
    # Keycode is composed of an integer + a string
    # If we hit escape, release the keyboard

    if keycode[1] == 'escape':
        keyboard.release()
    if keycode[1] == 'enter': #press enter to play for the first time the .wav
        self.load_audio()
        self.play_audio()
    if keycode[1] == 'up':
        self.vol +=0.01
        print(self.vol)
    if keycode[1] == 'down':
        self.vol -=0.01
        print(self.vol)
    # Return True to accept the key. Otherwise, it will be used by
    # the system.
    return True



def load_audio(self):
    self.p = pyaudio.PyAudio()
    self.wf = wave.open('bbaf2n.wav',
                            'rb')  

def play_audio(self):
    self.stream = self.p.open(format=self.p.get_format_from_width(self.wf.getsampwidth()),
                              channels=self.wf.getnchannels(),
                              rate=self.wf.getframerate(),
                              output=True,
                              # frames_per_buffer=2048,
                              stream_callback=self.callback)

def callback(self, in_data, frame_count, time_info,status):

    data = self.wf.readframes(frame_count)

    datamul = numpy.fromstring(data, numpy.int16)

    #code for changing volume is missing

    vol = vol.astype(numpy.uint16)  # volume


    if len(data)<2048:  #last time in the callback

      #In this point that the first sound has been completed I want to call self.play_audio 
      #for playing again the .wav file, while pressing enter it works.

        self.load_audio()
        self.play_audio() #it doesn’t  work 



        return vol.tostring(), pyaudio.paComplete


    return vol.tostring(), pyaudio.paContinue

0 个答案:

没有答案