Pygame sound keeps repeating - pygame

I am trying to play a sound at the end of a game when there is a lose. Previously this code below worked with Python 3.5 but it would abort after it played the sound. I upgraded to python 3.6 and now it just keeps on repeating. How can I play the sound until the end?
import pygame
def sound():
pygame.mixer.init()
sound1 = pygame.mixer.Sound('womp.wav')
while True:
sound1.play(0)
return

while True is an endless loop:
while True:
sound1.play(0)
The sound will be played continuously.
Use get_length() to get the length of the sound in seconds. And wait till the sound has end:
(The argument to pygame.time.wait() is in milliseconds)
import pygame
pygame.mixer.init()
my_sound = pygame.mixer.Sound('womp.wav')
my_sound.play(0)
pygame.time.wait(int(my_sound.get_length() * 1000))
Alternatively you can test if any sound is being mixed by pygame.mixer.get_busy(). Run a loop as long a sound is mixed:
import pygame
pygame.init()
pygame.mixer.init()
my_sound = pygame.mixer.Sound('womp.wav')
my_sound.play(0)
clock = pygame.time.Clock()
while pygame.mixer.get_busy():
clock.tick(10)
pygame.event.poll()

Related

I am trying to use this code based on mtcnn for face detection it is correct but it wont work

this code uses mtcnn for face detection from a frame
it usses opencv to draw boxes on detected faces
import cv2
from facenet_pytorch import MTCNN
import numpy as np
class FaceDetector(object):
def __init__(self,mtcnn):
self.mtcnn=mtcnn
```
.It seems that it is not getting inside the _draw()
def _draw(self,frame,boxes,probs,landmarks):
for box, prob,ld in zip(boxes,probs,landmarks):
#rectangle
print("in draw")
the opencv rectanle drawer
cv2.rectangle(frame,(box[0],box[1]),(box[2],box[3]),(0,0,255),thickness=2)
return frame
```
run() to run the app
def run(self):
cap=cv2.VideoCapture(0)
while True :
ret,frame= cap.read()
try :
boxes, probs,landamarks=self.mtcnn.detect(frame,landmarks=True)
self._draw(frame,boxes,probs,landmarks)
except :
pass
cv2.imshow("face detector",frame)
```
to stop the execution
if cv2.waitKey(1) & 0xFf==ord('q'):
break
cap.release()
cv2.destroyAllWindows()
main app
here we instanciate MTCNN and try to run it on our frame
mtcnn= MTCNN(keep_all=True)
fcd=FaceDetector(mtcnn)
fcd.run()

pyglet Python function will not return or bail

I am attempting a random sound looper to play bird calls to attract birds to my feeder. Where I am at in this process is just creating a function that will play a sound and then return. I intend to introduce pseudo-randomness both is volume and repetition next.
Here is the code I am using to attempt a function to play a random sound.
#!usr/bin/env python
#coding=utf-8
import pyglet
import os
import random
def playBirdSound():
target_dir = os.path.join(os.getcwd(), "birdcallSounds")
fileList = os.listdir(target_dir)
target_file = os.path.join(target_dir, fileList[random.randrange(0, len(fileList))])
song = pyglet.media.load(target_file)
song.play()
pyglet.app.run()
if __name__ == '__main__':
playBirdSound()
print("test trace print")
So far my I have only been able to get the a sound to play. But my function never returns to print my "test trace print".
pyglet.app.run() creates an infinite loop until the application is closed. Just move it to the end of the file.

How to get audio to stop on next scene?

import flash.media.Sound;
var sound1 = new MenuTheme();
sound1.play(1000);
Got this code to play, but now I want it to stop on its dedicated frame after I switch to a new one. How do I go about doing this?
if(currentFrame == 2(your dedicated frame)
{
sound1.stop();
}
One more thing, use a sound library, it helps a lot!

ActionScript : Sound from ByteArray has lag

In my application, I use the microphone to record and get the result in ByteArray, then, I convert it in playable Sound by using the WavSound class from org.as3wavsound.
Record and play work correctly except a huge lag at the launching of the sound ( Easily 2 secondes ).
My code is something like this :
import org.as3wavsound.WavSound;
import org.bytearray.micrecorder.encoder.WaveEncoder;
import org.bytearray.micrecorder.MicRecorder;
/* ... */
var wavEncoder:WaveEncoder = new WaveEncoder( 0.5 );
var recorder:MicRecorder = new MicRecorder( wavEncoder );
recorder.record();
/* ... */
recorder.stop();
var sound:WavSound = new WavSound( recorder.output );
/* ... */
sound.play();
Thanks a lot to help me understand what's wrong in it.
Looks like this is a known issue with the as3wavsound library: Delay When Playing Sound using as3wavsound
The answer on that post tells you to decrease the MAX_BUFFERSIZE in WavSoundPlayer to 2048.

Accurate BPM event listener in AS3

I'm trying to sync animation to music at a specific BPM. I've tried using the Timer but it isn't accurate when dealing with small intervals in milliseconds. I did some reading and found an alternate method that uses a small silent audio file and the SOUND_COMPLETE event as a Timer.
I used 167ms long sound file with this code.
package
{
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.media.Sound;
import flash.media.SoundChannel;
import flash.net.URLRequest;
public class BetterTimer extends EventDispatcher
{
private var silentSound:Sound;
public function BetterTimer(silentSoundUrl:String):void {
super();
silentSound = new Sound( new URLRequest(silentSoundUrl) );
silentSound.addEventListener(Event.COMPLETE, start);
}
public function start():void {
this.timerFired( new Event("start") );
}
private function timerFired(e:Event):void {
dispatchEvent( new Event("fire") );
var channel:SoundChannel = silentSound.play();
channel.addEventListener(Event.SOUND_COMPLETE, timerFired, false, 0, true);
}
}
}
This still doesn't stay on beat. Is the Flash Player capable of accuracy with sound?
You can also use the new Sound API with the SampleDataEvent and basically play your MP3 manually using Sound.extract(). In that case you know the latency up front and can even count up to the sample when your (delayed) event should happen.
This is what we do in the AudioTool and it works very well.
This is very tricky to get right! There's a small lib called BeatTimer that tries to do this. I haven't tried this code myself, but if it does what it claims it should be exactly what you need.
Setting the frame rate so that the event interval is a multiple of the frame rate might help (for example, 167ms equals 6 fps; 12, 18, 24 etc. are then also ok).
If I understood correctly, better solution would be to use the enterframe event. Instead of determining the position of the animation by counting the events, calculate it using elapsed time (getTimer or sound position). This would also make the animation work on slower computers that have lag.
I was looking through the popforge library's AudioBuffer and tried using one of the approach. That's the create a sync sound. The following is what i did.
var syncSamples:ByteArray = new ByteArray();
syncSamples.length = (2646000 / _bpm) << 1; /*44100*60=2646000*/
SoundFactory.fromByteArray(syncSamples, Audio.MONO, Audio.BIT16, Audio.RATE44100, soundInit);
The ms delay is pretty close, eg: at 120 BPM, it's between 509 - 512ms. The question is, am I going in the right direction?