Playing music from collection with SoundPlayer - c#

So I am doing a simple piano and trying to traverse the collection where I stored the notes, but the SoundPlayer doesn't want to play them properly in "without debugging mode", playing only the last one. However when I put a breakpoint there it plays all of them
public static List<MusicNote> music = new List<MusicNote>(15);
public static void PlayAll()
{
SoundPlayer sp = new SoundPlayer();
for (int i = 0; i <= music.Count - 1; i++)
{
string text = music[i].pitch.ToString();
sp.SoundLocation = (#"c:\my path here\" + text + ".wav");
sp.Play();
sp.Stop();
}
}
Pitch is simply ordinal number to link to file.
Thanks in advance

U better use PlaySyn in order to tell your program to wait until the music complete
// Create new SoundPlayer in the using statement.
using (SoundPlayer player = new SoundPlayer())
{
for (int i = 0; i <= music.Count - 1; i++)
{
string text = music[i].pitch.ToString();
sp.SoundLocation = (#"c:\my path here\" + text + ".wav");
// Use PlaySync to load and then play the sound.
// ... The program will pause until the sound is complete.
player.PlaySync();
}
}

I think its better when you use PlaySync(); instead of Play();
Because then you don't need the Stop() methode.
Here a link to the docu of SoundPlayer
Why use PlaySync? If you just call the Play method in this program, the program will terminate before the sound plays. The Sync indicates that the program should pause while the sound plays.

Related

How to play Multiple sound files from the properties using Sound Player

i am making a quiz and in each form i have background music and if they get an answer correct i want to play a sound effect. When i do this is stops the background music and plays the sound effect then no sound is playing, does anyone know how do it?
public static System.Media.SoundPlayer player = new System.Media.SoundPlayer();
public static void sound(string form)
{
switch (form)
{
case "Login":
player.Stop();
player.Stream = Properties.Resources._2marioloadscreen;
player.PlayLooping();
break;
}
}
Here's an example of how to do it, assuming you have two wav files (one for background music, and one for the correct answer sound effect). The key is to know when the sound effect is done playing, then continue with the background music again.
I wrote it as a simple C# Console App.
class Program
{
private static SoundPlayer player;
static void Main(string[] args)
{
using (player = new SoundPlayer())
{
player.SoundLocation = "bkgnd.wav";
player.PlayLooping();
Console.WriteLine("bkgnd.wav is now playing in a loop. (Hit ENTER key to start the hoorayyouwon.wav)");
Console.ReadLine();
Console.WriteLine("hoorayyouwon.wav is now playing.");
player.Stop();
player.SoundLocation = "hoorayyouwon.wav";
player.PlaySync(); // this ensures the hoorayyouwon.wav plays completely before it gets to the next line of code.
Console.WriteLine("bkgnd.wav is now continuing (actually, starting over). (Hit ENTER key to exit)");
player.SoundLocation = "bkgnd.wav";
player.PlayLooping();
Console.ReadLine();
}
}
}

c# - how to remove the interval between two timer ticks

I am using timer to connect several audio files together. There are a list of audio files and the timer will read files one by one. Once there is an audio read, it will be played. The goal is to play the audio file right after the previous one when it is finished(without any break).
(I am using Naudio)
Here is the code:
private void timer_key_Tick(object sender, EventArgs e)
{
if(!isPlaying)
{
//play the current audio
DirectSoundOut dso = sounds2[key_indexer];
dso.Play();
targetMusics.Add(dso);
}
else
{
foreach (DirectSoundOut dso in targetMusics)
{//stop the current audio
dso.Stop();
}
targetMusics.Clear();
key_indexer++; //switch to the next audio
if (key_indexer >= myMT.Keys.Count)
{
key_indexer = 0;
timer_key.Stop();
}
}
isPlaying = !isPlaying;
}
However, the fact is, when the first music finished, the second one didn't play at once. It comes after one second break. Is this the problem about timer itself? How should I change it?
Thanks for the help from #HansPassant. I made a mistake about logic in this timer. Here is the correct code after I applied his suggestion:
//stop the current playing
foreach(DirectSoundOut d in targetMusics)
{
d.Stop();
}
targetMusics.Clear();
//stop the entire process
if (key_indexer >= myMT.Keys.Count)
{
key_indexer = 0;
timer_key.Stop();
}
else
{ //play the current audio
DirectSoundOut dso = sounds2[key_indexer];
targetMusics.Add(dso);
dso.Play();
key_indexer++;
}

How to close Window Media Player after it is finish playing?

I want to know how to close the media player when it finishes playing my wav file. Because if I run this multiple times, it consumes an dangerous amount of computer ram. If you can solve that without closing it, by all means tell me.
var player = new WMPLib.WindowsMediaPlayer();
player.URL = #"D:\notes\01.wav";
This is the code to play it.
There isn't a way to exit the player, the only(not so ideal approach) is to kill it.
var proc = Process.GetProcessesByName("wmplayer");
if (proc.Length > 0) {
proc[proc.Length - 1].Kill();
}
This might do the trick for you
var player = new WMPLib.WindowsMediaPlayer();
player.URL = #"D:\notes\01.wav";
Thread.Sleep(2000);
player.controls.stop();
player.close();
Edit
Than you can kill the process and stop the WMPlayer
var prc = Process.GetProcessesByName("wmplayer");
if (prc.Length > 0) prc[prc.Length - 1].Kill();

audio.Play() not working

I have the a script called Timer.cs. This script is connected to some GUI Text, which displays the amount of time remaining in the game.
Also attached to this script is an Audio Source with my desired sound selected. When the clock reaches zero, the text changes to say "GAME OVER!" and the character controls lock up; however, the sound does not play.
All other instances of audio.Play() in my scene are working fine, and when I set the Audio Source to "Play On Awake", it plays without a problem. What could be the problem?
Using UnityEngine;
using System.Collections;
public class Timer : MonoBehaviour {
public float timer = 300; // set duration time in seconds in the Inspector
public static int sound = 1;
public static int go = 1;
bool isFinishedLevel = false; // while this is false, timer counts down
void Start(){
PlayerController.speed = 8;
PlayerController.jumpHeight = 12;
}
void Update (){
if (!isFinishedLevel) // has the level been completed
{
timer -= Time.deltaTime; // I need timer which from a particular time goes to zero
}
if (timer > 0)
{
guiText.text = timer.ToString();
}
else
{
guiText.text = "GAME OVER!"; // when it goes to the end-0,game ends (shows time text over...)
audio.Play();
int getspeed = PlayerController.speed;
PlayerController.speed = 0;
int getjumpHeight = PlayerController.jumpHeight;
PlayerController.jumpHeight = 0;
}
if (Input.GetKeyDown("r")) // And then i can restart game: pressing restart.
{
Application.LoadLevel(Application.loadedLevel); // reload the same level
}
}
}
Given that you are calling it as part of your Update routine, I'd have to guess that the problem is you calling it repeatedly. I.e. you're calling it every frame as long as timer <= 0.
You shouldn't call Play() more than once. Or at least not again while it is playing. A simple fix would be something along the lines of
if(!audio.isPlaying)
{
audio.Play();
}
See if that solves your problem, and then you can take it from there.
I had error using audio.Play(); and used following it fixed the error for me
GetComponent<AudioSource>().Play();

XNA C# SoundEffectInstance - no sound

I'm trying to play SoundEffectInstances of loaded .wav files in my game, but I hear no sound whatsoever.
I have a class "ETSound"; for which each object holds one sound. So one ETSound object might hold the 'menu open' sound, and another might hold the 'tank firing' sound... Etc.
Anyway, the ETSound constructor looks like this:
public ETSound(SoundEffect se, float volume, float pitch, bool looped, int soundPriority) {
soundTemplate = se;
this.volume = volume;
this.pitch = pitch;
this.looped = looped;
if (soundPriority > 0) {
if (soundPriority > 64) soundPriority = 64;
instanceArray = new SoundEffectInstance[soundPriority];
nextInstanceIndex = 0;
for (int i = 0; i < soundPriority; ++i) {
SoundEffectInstance sei = soundTemplate.CreateInstance();
sei.Volume = volume;
sei.Pitch = pitch;
instanceArray[i] = sei;
}
}
}
This basically sets up some parameters, and creates an array of sound effect instances according to the supplied SoundEffect.
Then, I'm calling the Play() function of ETSound:
public void Play() {
if (instanceArray[nextInstanceIndex].State != SoundState.Stopped) instanceArray[nextInstanceIndex].Stop();
instanceArray[nextInstanceIndex].Play();
if (++nextInstanceIndex >= instanceArray.Length) nextInstanceIndex = 0;
}
However, nothing happens. I hear nothing.
Can anyone tell me what's going wrong? Thanks.
Sorry, everyone... Turns out the .wav file I was using to test was corrupt... A tough bug to find, but I got it. Thanks anyway.

Categories