jjyj
jjyj

Reputation: 459

Python 3.6: How to play audio faster

So, I have this bit of code that print out text in a delayed fashion like you see in some old school or indie video games.

Everything is working, but not the way I want it to. I want the printing and the playing of the sound to be faster as right now it is too slow.

Is there any way to make this possible?

Here is my code:

Note: This lags in pycharm but works fine in terminal/cmd.

import sys
import time
from pydub import AudioSegment
from pydub.playback import play



def print_delay(string_in):
    sound_1 = "text_beep.wav"
    sound_play = AudioSegment.from_wav(sound_1)


    for char in string_in:
        sys.stdout.write(char)
        sys.stdout.flush()
        play(sound_play)

        if char != ",":
            time.sleep(0.01)
        if char == ".":
            time.sleep(0.20)
        if char == ",":
            time.sleep(0.10)

    print("\n")

string_hello = "Hello World, this is a sample text.\nI want want this to print out faster without being delayed by the sound file.\nIs there any faster way to do this?"

print_delay(string_hello)

Upvotes: 2

Views: 3239

Answers (1)

jjyj
jjyj

Reputation: 459

Woohoo! Ok I figured it out.

Use the module named: "pyglet"

Im not 100% sure but it looks like pyglet lets you specify that your sound file is a short sound. If this is the cases then you can pass the argument "streaming = False" which basically tells it to play the sound immediately and in turn use less CPU power. I'm not sure if this is what is making the sound file play the way I want it to but it might.

If anyone knows for sure please let me know.

Here is my source: https://pythonhosted.org/pyglet/programming_guide/playing_sounds_and_music.html

import sys
import time
import pyglet



def print_delay(string_in):
    sound_1 = pyglet.resource.media("text_beep.wav", streaming=False)


    for char in string_in:
        sound_1.play()
        sys.stdout.write(char)
        sys.stdout.flush()

        if char != ",":
            time.sleep(0.05)
        if char == ".":
            time.sleep(0.70)
        if char == ",":
            time.sleep(0.50)


    print("\n")

string_hello = "Hello World, this is a sample text.\nI want want this to print out faster without being delayed by the sound file.\nIs there any faster way to do this?"

print_delay(string_hello)

Upvotes: 2

Related Questions