How to add audio only when mousepressed in processing? - audio

I was wondering if there was a processing code that will let me use sound only when i press the mouse and stops when I release it. I already have the audio that I want to use loaded onto processing but I'm having difficulty finding the code. Please help me! Thank you!

Your question is very vague, but I'll do my best to answer.
I don't think there's any way to handle audio with Processing's built-in functions, but the minim library works well with it. I'm going to assume that's what you're using for this solution.
As I understand it, you'd like to press the mouse, start the sound, and when the mouse is released you'd like to stop the sound, rather than pause it. We can accomplish this using processing's built-in mousePressed and mouseReleased methods like so:
import ddf.minim.*;
Minim minim;
AudioPlayer player;
AudioInput input;
void setup()
{
//let's make the window a little bigger
size(400,400);
minim = new Minim(this);
player = minim.loadFile("song.mp3");
input = minim.getLineIn();
}
void draw(){ }
void mousePressed()
{
player.play();
}
void mouseReleased()
{
player.close();
//since close closes the file, we'll load it again
player = minim.loadFile("song.mp3");
}
The code for pausing would look very similar, except you would replace everything in the mouseReleased block with the following:
player.pause();

Related

Javafx how to setup a Media playlist

Ok I'm currently doing a Trivial Pursuit game project with javafx and my group wants me to add audio the problem is I have a method
public static void playSoundEffect(Sound sfx) {
Media media=null;
try {
media = new Media(GameAudio.class.getClassLoader().getResource(sfx.getSound()).toURI().toString());
mediaPlayer = new MediaPlayer(media);
mediaPlayer.play();
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
But it has its issues because if I want to mute all the audio, only the last played sound will be muted and not the whole project's audio.
I was thinking of making 2 List of MediaPlayer(SFX and Music) that contains each audio files but I'm not sure how to set this up properly... My current try was using Enum for the const strings containing the path. Then in some class i use the method above to play the sound at a certain point. But since i always call a new instance of mediaPlayer I don't have any control on it anymore and that's why I'm so lost.
As #James_D supposed for the mute I will use a BooleanProperty muted and call a method mediaPlayer.muteProperty().bind(muted) on each mediaplayer created.

IrrKlang Sound Library and Stop Event threads

I have a question about using external c++ library (irrKlang.dll) which is an audio playback engine. Now, the problem is that when I get a SoundStopped event out of it, and do an action in the main form, all kinds of stack related errors arise. Let me show the code:
namespace WindowsFormsApplication4
{
public class IsoundFinished : ISoundStopEventReceiver
{
public delegate void OnSoundStoppedEventHandler(object source, EventArgs e);
public event OnSoundStoppedEventHandler IStopped;
public void OnSoundStopped(ISound iSound, StopEventCause reason, object userData)
{
if (reason.ToString() == "SoundFinishedPlaying")
IStopped?.Invoke(this, EventArgs.Empty);
}
}
}
That is an extended class for me to do custom actions (for example - if sound finished, raise the event...) I am creating an instance of it, for the event action to get exposed in my main Form1 class:
IsoundFinished iStopReceiver = new IsoundFinished();
Now in my main form, I have this line in my Form1() method, just under my InitializeComponent():
iStopReceiver.IStopped += new soundFinished.OnSoundStoppedEventHandler(OnStopped);
It's for subscribing to the event handler. And finally - my OnStopped() method which is supposed to do stuff when the song ends it's playback - it's on the same Form1:
private void OnStopped(object sender, EventArgs e)
{
if (InvokeRequired)
{
Invoke(new Action<object, EventArgs>(OnStopped), sender, e);
return;
}
btnStop1.PerformClick();
}
My Stop1 button method is (for those who work with the IrrKlang) ISound.Stop(); and few more lines of code, dealing with the display of playlist and so on. Although I have invoked it from the main UI thread - which should provide me with some degree of thread misalignment protection, all kinds of errors appear, mostly
Cannot evaluate expression because a native frame is on the top of the call stack.
Of course, if I do it without event handler, ISound.Stop(); drops the sound from the engine, like it should. I know something wrong is happening with the threads, but I can't figure out what's going on. If someone would give me few tips, I'd appreciate that a lot.
Well it seems I've solved it myself ! It's all about understanding how the threads are working in Visual C#. The problem was this : I was actually PAUSING the background thread where my audioengine was triggering the event - so 'till I performed an action after INVOKE in the main UI thread, background thread was paused along with the whole irrKlang engine. It was unable to purge itself properly, so it's call stack got clogged!
Using BEGININVOKE solved the problem, as it doesn't PAUSE the background task. It lets it run instead. Diagram on this answer gave me much needed piece of info I was looking for.
Maybe someone will need this answer too, glad I helped myself :P
private void OnStopped(object sender, EventArgs e)
{
if (InvokeRequired)
{
BeginInvoke(new Action<object, EventArgs>(OnStopped), sender, e);
return;
}
btnStop1.PerformClick();
}

Unity sound not playing

I'm trying to play a sound, but it's not playing
Here's my code:
public void Replay()
{
playAudio ();
Application.LoadLevel (Application.loadedLevel);
}
void playAudio()
{
AudioSource audio = GetComponent<AudioSource> ();
audio.Play();
}
When a button clicked, I'm calling Replay(). But, the sound is not played.
If I remarkedApplication.LoadLevel (Application.loadedLevel);, the sound plays normally.
What should I do to make the sound play with Application.LoadLevel()?
The AudioSource playing the sound will get removed before it has time to finish.
Here is an alternative solution using yield to wait for the sound to finish.
public void Replay()
{
StartCoroutine("ReplayRoutine");
}
IEnumerator ReplayRoutine()
{
AudioSource audio = GetComponent<AudioSource>();
audio.Play();
yield return new WaitForSeconds(audio.clip.length);
Application.LoadLevel(Application.loadedLevel);
}
You call play method and you load the scene after it. Try to call playAudio() before loading level.
public void Replay() {
Application.LoadLevel(Application.loadedLevel);
playAudio();
}
I think you don't give the chance to the audio source to play the sound, because after executing play, you immediately re-loaded the scene, so the same instance of audio source does not exist anymore, a new instance is created which has not yet received the play command. You can use some small delay using co-routine or other ways to give the needed time to the audio source. ( If you want to play the sound before loading level, otherwise just play the sound in a Start() callback)

processing, sound overlapping

I have some problems to understand how to play some tracks
one after the other avoiding the overlap effect.
I am using the Minim library but I did not find a way
to detect the final moment of the first sound to start the second one.
Can anybody give me my some tips?
this is my sketch
import ddf.minim.*;
Minim minim;
AudioPlayer player[]=new AudioPlayer[4];
String filenames[] = new String[]{"sound1.mp3", "sound2.mp3"};
void setup(){
minim = new Minim(this);
for(int i=0;i<2;i++){
player[i] = minim.loadFile(filenames[i]);
player[i].play();
print(filenames);
}
}
void draw(){}
void stop(){
for(int i=0;i<2;i++){
player[i].close();
}
minim.stop();
super.stop();
}
You can poll player[i].isPlaying() to see if the sound is still playing before starting the next one. In your code, this means keeping track of which player is currently active, and moving the call to the .play() method into draw().

how to invoke an event on a key press

I am making a gambling game in graphics. There are three polygons on screen reading below 3, above 3 and throw a dice. I will incorporate random function generator in throw a dice area. And define two functions when a user enters the area of the rest of two polygons. But I am facing the problem of how to add functions here and how to invoke those function on keypress. Please suggest.
I think should have mentioned the language you are using to code, In case of java swing i have a good solution.
Depending on where you want to trap the "enter" key, you could use an ActionListener (on such components such as text components or buttons) or attach a key binding to your component.
Here is the link how to use Key binding
public class MyPanel extends JPanel {
public MyPanel() {
InputMap im = getInputMap(WHEN_FOCUSED);
ActionMap am = getActionMap();
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "onEnter");
am.put("onEnter", new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
// Enter pressed
}
});
}
}
Actually i didn't understand your question, secondly if you are trying to nesting the events you can use threading i have link --Threading with swing.
you can check your question context here and apply it.
Ok and this is all for java, if you are working with other prog. language then please comment.
Thanks..

Resources