简体   繁体   中英

Kivy doesn't play sound file the first time play() is called

I run a simple Kivy app on Windows. A button executes following method from the Kivy docs ( link ) when pressed:

def play_audio(self):
    sound = SoundLoader.load('output.wav')
    if sound:
        print("Sound found at %s" % sound.source)
        print("Sound is %.3f seconds" % sound.length)
        sound.play()

The first time the button is pressed, it either plays about half a second of sound and then immediately stops or it's not playing anything at all. When I press the button again it plays the entire file as expected.

Why isn't it playing the file on the first button press and how do I get it to work properly?

Any help is greatly appreciated.

I think this thread will be useful. Try loading the sound once before the button is even pressed like so:

from kivy.core.audio import SoundLoader
from kivy.base import runTouchApp
from kivy.uix.button import Button
import time

sound = SoundLoader.load('output.wav')
sound.seek(0)

class MyLabel(Button):
    def on_release(self):
        start_time = time.time()
        self.play_sound()
        print("--- %s seconds ---" % (time.time() - start_time))

    def play_sound(self):
        if sound:
            print("Sound found at %s" % sound.source)
            print("Sound is %.3f seconds" % sound.length)
            sound.play()

runTouchApp(MyLabel(text="Press me for a sound"))

The play_sound() function took about ten times less time to complete on my machine if you do sound.seek(0) .

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