orangeInk
orangeInk

Reputation: 1400

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.

Upvotes: 1

Views: 1825

Answers (1)

Edvardas Dlugauskas
Edvardas Dlugauskas

Reputation: 1489

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).

Upvotes: 1

Related Questions