How can I hide 'pydub' output information?

Question:

My Code

from pydub import generators
from pydub.playback import play

play(generators.Sine(440).to_audio_segment(duration=1500))

In the console output:

Input #0, wav, from '/var/folders/_7/0q83l2vn4zjd7zgqpy3v97840000gn/T/tmphlm6i9s_.wav':
Duration: 00:00:01.50, bitrate: 705 kb/s
Stream #0:0: Audio: pcm_s16le ([1][0][0][0] / 0x0001), 44100 Hz, 1 channels, s16, 705 kb/s
Asked By: Birkan

||

Answers:

I’m currently having a problem with my computer, so I’m not able to check this, but this should work:

from pydub import generators
from pydub.playback import play
import subprocess, sys

play(generators.Sine(440).to_audio_segment(duration=1500))
if sys.platform in ('linux', 'osx'):
    subprocess.call('clear', shell=True)
elif sys.platform in ('nt', 'dos', 'ce'):
    subprocess.call('cls', shell=True)
else:
    pass

This is kind-of a ‘hack’ in the code that just clears console every time an output is sent.
Something like this may work, but again, I haven’t been able to test it:

import contextlib
import io

from pydub import generators
from pydub.playback import play

with contextlib.redirect_stdout(io.StringIO()):
    play(generators.Sine(440).to_audio_segment(duration=1500))
Answered By: StevenHarvey

I didn’t find a solution yet, but I found besides "pydub" three alternatives. The last one is without output text. (Number-4)

import time
from gtts import gTTS
tts = gTTS('Test', lang='en')
tts.save('Test.mp3')

#=================1
print("1")
from pygame import mixer
mixer.init()
mixer.music.load("Test.mp3") 
mixer.music.play()
time.sleep(1)

#=================2
print("2")
from pydub import AudioSegment
from pydub.playback import play
path_to_file = r"Test.mp3"
song = AudioSegment.from_mp3(path_to_file)
play(song)
time.sleep(1)

#=================3
print("3")
import os
os.system("mpg321 -q Test.mp3")
time.sleep(1)

#=================4
print("4")
from mpyg321.mpyg321 import MPyg321Player
player = MPyg321Player()
player.play_song("Test.mp3")
time.sleep(1)
Answered By: Birkan

See the request discussion on github: https://github.com/jiaaro/pydub/issues/247 (I think it’s still to do). But following annaproxy you can modify _play_with_ffplay in pydub.playback to redirect stdout and stderr to devnull.

Answered By: rammy

I find none of the answers mentioned above work.

I finally managed to hide the pydub playback output by using a subprocess.

If you are interested, I implemented at:

https://github.com/eliranwong/UniqueBible/blob/main/util/RemoteCliMainWindow.py#L287

Answered By: eliranwong
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.