时不会播放声音文件

时不会播放声音文件

本文介绍了Kivy在第一次调用play()时不会播放声音文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Windows上运行了一个简单的Kivy应用程序.当按下按钮时,将从Kivy文档(链接)中执行以下方法:

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?

非常感谢您的帮助.

推荐答案

我认为线程将很有用.甚至在按下按钮之前尝试加载一次声音,如下所示:

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

如果您执行sound.seek(0),则在我的计算机上完成play_sound()功能所需的时间大约减少了十倍.

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

这篇关于Kivy在第一次调用play()时不会播放声音文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-16 01:32