Program not playing sound - python

I am programmin a text based game in Python and I want to play effects music over the battle music, I have written the following module to play sounds
#Music.py:
#V2
import winsound as ws
def playS(a):
p=("C:\\Users\\user\\OneDrive\\Desktop\\Game\\soundLibrary\\"+(a)+".wav")
ws.PlaySound(p,ws.SND_ASYNC)
def playE(a):
p=("C:\\Users\\user\\OneDrive\\Desktop\\Game\\soundLibrary\\"+(a)+".wav")
ws.PlaySound(p,ws.SND_NOSTOP)
When the function playE('effect') is played the following error message is returned
File "c:\Users\user\OneDrive\Desktop\Game\Music.py", line 10, in playE
ws.PlaySound(p,ws.SND_NOSTOP)
RuntimeError: Failed to play sound
If anyone could say why it would be appreciated.
(note: playS() works fine)

Playsound doesn't actually let you play two sounds simultaeneously, hence it is returning an error.

Related

Random.Choice always the same result

Some pretext that's maybe useful idk. I use mixer and am trying to do a random music choice but the random.choice always take the last one (song 5). This is my code
if Mamp=='1':
vad=input("[1] Bakground music")
#Mixer shit
mixer.init()
pygame.mixer.get_init
if vad=='1':
commands=[mixer.music.load("song1.mp3"), mixer.music.load("song2.mp3"),mixer.music.load("song3.mp3"),mixer.music.load("song4.mp3"),mixer.music.load("song5.mp3")]
current_command=random.choice(commands)
current_command
mixer.music.play(0)
I looked at many answers for the same problem but all wer're just fixing thier (the uploader's) code and uploaded it so I couldn't use it for my code. And since i'm trying to learn python it would be great if you could also explain what went wrong?
commands=[mixer.music.load("song1.mp3"), ...]
current_command=random.choice(commands)
current_command
You're doing this part all wrong.
It seems like you want to make a list of commands to be executed later, but that's not what you're actually doing. The load() commands are actually executed when the commands list is created.
And because song5.mp3 is the last one, it gives the appearance of being "picked" every time.
Try it this way instead:
songs = ["song1.mp3", "song2.mp3", "song3.mp3", "song4.mp3", "song5.mp3"]
song = random.choice(songs)
mixer.music.load(song)

Python av play file in infinite loop

Using https://pypi.org/project/av/ trying to open file for infinite playback.
But the cycle ends with the last frame.
After searching and reading manuals, test code looks as follows:
(Note: these options are expected to be passed down to aiortc.contrib.media.MediaPlayer and work similarly):
import av
av.open(file="file.mp4", options={"fflags": "+genpts", "loop": "-1"})
for frame in media.decode():
print(frame)
Question: What should be the options (and if it is possible) to play file in infinite loop? (NOT just once)
According to the documentation, you create a MediaPlayer using the parameter loop=True
from aiortc.contrib.media import MediaPlayer
player = MediaPlayer(file="file.mp4", options={"fflags": "+genpts"}, loop=True)
You don't need to call PyAV yourself. It is done in MediaPlayer (see source code).

Jupyter / Colab : Play sound with any error in any cell + Play sound after completing long running cells

Sometimes an error happens but I don't notice because I may be running multiple cells at once.
I'd like errors to play a sound.
In other words, play a sound when the execution fails, an Exception is raised, when execution errors are found, etc.
Many people would like long running cells to play a sound when completed.
COLAB
I mixed the solutions I found in some places 1 2 3 4
a) Create a global exception handler that beeps on errors
b) Create a simple function that you place at the end of the long-running cell (some other approaches on links)
You can change the sounds to anything you like.
Note: The sounds inside the Exception Handler and the beep_completed() are very different and with reason. The first is short and non-annoying and the second is long and pleasant (in case you are away from computer so you clearly hear that the task is completed). In any case you can replace them.
Note: There is a line that only applies to Colab. If you can provide the one for Jupyter I will gladly update the answer.
# This line is specific for Colab (please provide alternative for Jupyter)
from google.colab import output
from IPython.core.ultratb import AutoFormattedTB
# Catch any Exception, play error sound and re-raise the Exception
#-------------------------------------------------
# initialize the formatter for making the tracebacks into strings
itb = AutoFormattedTB(mode = 'Plain', tb_offset = 1)
# this function will be called on exceptions in any cell
def custom_exc(shell, etype, evalue, tb, tb_offset=None):
# still show the error within the notebook, don't just swallow it
shell.showtraceback((etype, evalue, tb), tb_offset=tb_offset)
# Play an audio beep. Any audio URL will do.
output.eval_js('new Audio("http://soundbible.com/grab.php?id=419&type=wav").play()')
# # grab the traceback and make it into a list of strings
# stb = itb.structured_traceback(etype, evalue, tb)
# sstb = itb.stb2text(stb)
# print (sstb) # <--- this is the variable with the traceback string
# print ("sending mail")
# send_mail_to_myself(sstb)
# this registers a custom exception handler for the whole current notebook
get_ipython().set_custom_exc((Exception,), custom_exc)
#------------------------------------------
# Function to play a sound (to put at the end of a long job)
def beep_completed():
#url_sound="http://soundbible.com/grab.php?id=1795&type=mp3";
output.eval_js('new Audio("http://soundbible.com/grab.php?id=1795&type=mp3").play()')
# Just play it with
beep_completed()
Jupyter
Comment out as needed. If you want to use a local file, you have to download it first and maybe adjust the path.
from IPython.display import Audio, display
# ----- error sound --------
def play_sound_error(self, etype, value, tb, tb_offset=None):
self.showtraceback((etype, value, tb), tb_offset=tb_offset)
v1="http://soundbible.com/grab.php?id=419&type=wav" # Short Error Beep sound
v2="https://wav-sounds.com/wp-content/uploads/2017/09/Various-02.wav" # Short Baby cry
display(Audio(url=v1, autoplay=True))
v1="../sound_error_beep.wav" # Short Error Beep sound
v2="../sound_baby_cry.wav" # Short Baby cry
display(Audio(filename=v1, autoplay=True))
# ----- atach it to all Exceptions
get_ipython().set_custom_exc((Exception,), play_sound_error)
# ----- success sound --------
def play_sound_success():
v1='http://soundbible.com/grab.php?id=1795&type=wav'
#display(Audio(url=v1, autoplay=True))
display(Audio(filename='../sound_success.wav', autoplay=True))
Since in my use cases, the set_custom_exc solution was not acceptable as it did override the previously established custom exceptions, I have created a small notification package that works for both regular scripts (using sys.excepthook) and jupyter notebooks (using post_run_cell).
Furthermore, since I did not like to have a Jingle Bell situation when the cells crash immediately, I have added a customizable minimum time interval based on either the total execution time (when in scripts) or the cell execution time (when in notebooks).
The package comes both as import oneliners such as:
import ringbell.auto
Which will play a sound if the execution takes more than a minute.
Or for immediate notification:
import ringbell.immediate
Or, for notifications exclusively on exceptions:
import ringbell.all_exceptions
You can also use it to play a sound whenever you like, by importing the RingBell class and going:
from ringbell import RingBell
RingBell(
sample = "microwave",
minimum_execution_time = 0,
verbose = True
)
You can get it from PyPi by running:
pip install ringbell

why no sound when I use CompositeAudioClip in python moviepy?

here is the python script.
from moviepy.editor import *
videoclip = VideoFileClip("1_0_1522314608.m4v")
audioclip = AudioFileClip("jam_1_Mix.mp3")
new_audioclip = CompositeAudioClip([videoclip.audio, audioclip])
videoclip.audio = new_audioclip
videoclip.write_videofile("new_filename.mp4")
then returned
[MoviePy] >>>> Building video new_filename.mp4 [MoviePy] Writing audio
in new_filenameTEMP_MPY_wvf_snd.mp3
100%|████████████████████████████████████████| 795/795 [00:01<00:00,
466.23it/s] [MoviePy] Done. [MoviePy] Writing video new_filename.mp4 100%|███████████████████████████████████████| 1072/1072 [01:26<00:00,
10.31it/s] [MoviePy] Done. [MoviePy] >>>> Video ready: new_filename.mp4
1_0_1522314608.m4v and jam_1_Mix.mp3 they both have sound.
but the new file new_filename.mp4 no sound.
did I do something wrong? please help. thank you.
I had similar issues. I found that sometimes the audio is in fact present, but will not be played by all players. (Quicktime does not work, but VLC does).
I finally use something like :
video_clip.set_audio(composite_audio).write_videofile(
composite_file_path,
fps=None,
codec="libx264",
audio_codec="aac",
bitrate=None,
audio=True,
audio_fps=44100,
preset='medium',
audio_nbytes=4,
audio_bitrate=None,
audio_bufsize=2000,
# temp_audiofile="/tmp/temp.m4a",
# remove_temp=False,
# write_logfile=True,
rewrite_audio=True,
verbose=True,
threads=None,
ffmpeg_params=None,
progress_bar=True)
A few remarks :
aac seems to work better for quicktime than mp3.
logfile file generation helps to diagnose what is happening behind the scenes
temp_audiofile can be tested on its own
set_audio() returns a new clip and leave the object on which it is called unchanged
Setting the audio clip duration to match the video helps :
composite_audio = composite_audio.subclip(0, video_clip.duration)
composite_audio.set_duration(video_clip.duration)

pyglet ManagedSoundPlayer on_eos event not working?

I am trying to listen to the on_eos event of the pyglet.media.ManagedSoundPlayer following the examples in the pyglet documentation and end up with code like this:
from pyglet.media import load, ManagedSoundPlayer
def on_eos():
print "EOS"
def play(source):
player = source.play()
player.on_eos = on_eos
src = load("beep.mp3")
play(src)
As expected, I do hear a "beep" - but to my surprise and frustration, "EOS" is not printed.
Did I miss something in the docs? Am I doing something wrong? What should I do to make this work?
Thank you!
Accordingly to this old link to pyglet Google group you need some tricks to reuse on_eos. It is still not implemented. Take a look on the sample from documentation how to implement on_eos event: http://www.pyglet.org/doc/programming_guide/media_player.py

Categories

Resources