I'm working on a music player, it finds from web, downloads the bytes async, plays it, and when the program closes, it deletes all downloaded musics. So, it downloads temporarily.
I want to play the music while it was downloading. i guess it can be done from
private static void Downloader_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
}
this but this e only shows the percentage, not downloaded bytes. It's something like loading a video from youtube, you can watch it even not fully loaded. I trying to make it happen with musics.
Related
I am trying to get an event when a file is added on the "camera roll" album by a usb connection.
I thought in create a task to verify if the "camera roll" album is increasing or decreasing their size. But this will be very cost in the performance. So i am trying to find an event that tells me when the system file be altered.
Anyone can help me?
WinRT provides files and folders monitoring based on queries, which is an alternative to the .net FileSystemWatcher class, your app also needs to be subscribed on the query's ContentsChanged event to get notified
private void MainPage_OnLoaded(object sender, RoutedEventArgs e)
{
var query = KnownFolders.CameraRoll.CreateFileQuery();
query.ContentsChanged += QueryContentsChanged;
await query.GetFilesAsync();
}
void QueryContentsChanged(Windows.Storage.Search.IStorageQueryResultBase sender, object args)
{
// your handler code
}
Update
the GetFilesAsync is necessary to trigger the ContentsChanged event.
tl;dr version: How can I start playing a sound in the MouseDown event of a WinForms button and stop it from playing in the same button's MouseUp event?
Intermediate C# dev here and I've been trying to write a simple Simon clone.
I'm currently stuck trying to make it play the sound for the colored button only while the user is clicking the button. (I use "button" and "tile" interchangeably. Both refer to the colored button the user will press on the form)
I originally tried this:
public partial class frmMain : Form
{
private SoundPlayer soundPlayer;
private void btnGreenTile_MouseDown(object sender, MouseEventArgs e)
{
soundPlayer = new SoundPlayer(Properties.Resources.greenTileSound)
soundPlayer.Play();
}
private void btnGreenTile_MouseUp(object sender, MouseEventArgs e)
{
soundPlayer.Stop();
}
}
But this didn't stop the sound because the MouseUp event didn't fire due to MouseDown not being finished (still playing the sound which is like 5 seconds long in case someone holds the button for longer than a simple click). As mentioned by Luis Tellez in the comments, SoundPlayer plays the sound on it a new thread...so I have no idea why this code doesn't work now.
So I looked into multithreading and tried this:
public partial class frmMain : Form
{
private Thread soundThread = new Thread(new ParameterizedThreadStart(PlaySound));
// Create stream objects for each sound (needed to allow SoundPlayer to use Resources)
private Stream greenTileSound = Properties.Resources.greenTilePress;
private Stream redTileSound = Properties.Resources.redTilePress;
private Stream yellowTileSound = Properties.Resources.yellowTilePress;
private Stream blueTileSound = Properties.Resources.blueTilePress;
public frmMain()
{
InitializeComponent();
}
private void btnGreenTile_MouseDown(object sender, MouseEventArgs e)
{
soundThread.Start(greenTileSound);
}
private void btnGreenTile_MouseUp(object sender, MouseEventArgs e)
{
soundThread.Abort();
}
// Have to use object as parameter because ParamterizedThreadStart() only takes object arguments
private static void PlaySound(object soundToPlay)
{
SoundPlayer soundPlayer = new SoundPlayer((Stream)soundToPlay);
soundPlayer.Play();
}
}
With the above code, it does not stop playing the sound on MouseUp, and even better it throws a ThreadStateException with the message "Thread is running or terminated; it cannot restart."
As you can probably tell, I only just learned about multithreading while trying to write this code. I have to use ParameterizedThreadStart because the method it calls when the thread starts, PlaySound(), needs to pass a parameter to soundPlayer with the resource corresponding to the colored button that was pressed by the player (a .wav file).
I then thought maybe I should try using soundThread.Suspend() instead of soundThread.Abort() but Suspend is deprecated...
Can anyone point me in the right direction to get the sound to stop on MouseUp? Do I need to work with multithreading? I think my problem just comes down to logic but I am fully stuck. Thank you for any and all help! :)
As a side note, I'm kind of surprised that this question or something similiar has not been asked yet (at least I couldn't find it with google searches or stackExchange searches).
You can see in the documentation that the play() method run in other thread, you can do something else after it and it should run, so your problem with the first approach is something different from what you were thinking.
The Play method plays the sound using a new thread. If you call Play
before the .wav file has been loaded into memory, the .wav file will
be loaded before playback starts. You can use the LoadAsync or Load
method to load the .wav file to memory in advance. After a .wav file
is successfully loaded from a Stream or URL, future calls to playback
methods for the SoundPlayer will not need to reload the .wav file
until the path for the sound changes. If the .wav file has not been
specified or it fails to load, the Play method will play the default
beep sound.
http://msdn.microsoft.com/en-us/library/system.media.soundplayer.play%28v=vs.110%29.aspx
I am fairly new to C# and Mark's library NAudio. So I've tried learning by myself and I've come up with an basic audio player. But I have a problem.
When trying to load big files in the player the app freezes for 2-10 seconds while loading the entire file (I suppose). This is my code for reading the file:
if (target.EndsWith("mp3") || target.EndsWith("Mp3") || target.EndsWith("MP3"))
{
NAudio.Wave.WaveStream pcm = NAudio.Wave.WaveFormatConversionStream.CreatePcmStream(new NAudio.Wave.Mp3FileReader(target));
stream = new NAudio.Wave.BlockAlignReductionStream(pcm);
}
All I really want is to read the file in parts. Like a buffer. Read 10 seconds from the HDD to RAM memory, then after those 10 seconds run out, read the next 10 seconds, and so on. I think this should resolve the freeze issue I have with large files.
The cause of the delay is that Mp3FileReader creates a table of contents to allow it to determine the file length and to enable quicker repositioning. You could try using MediaFoundationReader instead which would be quicker, but won't work on Windows XP.
all programs have delay to load big files. this is depended to client computer speed.
but you can use backgroundWorker in your program and show a loading animation on your application Form during the file loading.
add backgroundWorker tool on your form
use this code on open button click:
backgroundWorker_name.RunWorkerAsync();
and put your code to the DoWork event
private void backgroundWorker_name_DoWork(object sender, DoWorkEventArgs e)
{
}
I've a really simple method for playing sound effects:
private void PlaySound(string file)
{
var sp = new SoundPlayer(#"Effects\" + file + ".wav");
sp.Play();
}
Then I do this to call it:
PlaySound("music");
Now, the first time PlaySound("music") gets called, it won't play it. The second time and all the other times after that it will.
Any ideas of what goes wrong here?
Try this:
private void PlaySound(string file){
using (SoundPlayer player = new SoundPlayer(#"Effects\" + file ' ".wav"))
{
// Use PlaySync to load and then play the sound.
player.PlaySync();
}
}
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.
You need to call the load method before playing.If the the file is not already loaded ,the file will be loaded with a call to Play.Which explains why the file is not played the first time.
If you call Play before the .wav file has been loaded into memory, the .wav file will be loaded before playback starts.-MSDN
Both Load and PlaySync will block the current thread.A better option would be to use the LoadAsync to load the file asynchronously.
I am currently implementing my final year project as a Music Software Development student.
I am making a software that plays a midi track that is generated earlier in the process.
In my interface, there is a button "play" and a button "stop".
When I click "play", a loop is called that plays this track. In this loop, I call a function from an instance of an other class.
What I would like is that when the user press "pause", the loop is temporary stopped, and when he press "pause" again, it goes back exactly where it was in the loop.
So far, when I press play, the track plays exactly how I want to, but I can't use any other element of my window until the loop is not completly processed.
Here is my code.
private void playStopButton_Click(object sender, RoutedEventArgs e)
{
// Initialising my output midi devices
outDevice.Send(new ChannelMessage(ChannelCommand.ProgramChange, information.bassChannel, information.bassSound));//bass
outDevice.Send(new ChannelMessage(ChannelCommand.ProgramChange, information.guitarChannel, information.guitarSound));//guitar
for (int barNum = 0; barNum < Globals.numberOfBars; barNum++)
{
// playing the first beat
rythmicPattern.play(0, ref outDevice, information, Globals.chordProgression.Bars[barNum].Chord);
//second beat
rythmicPattern.play(1, ref outDevice, information, Globals.chordProgression.Bars[barNum].Chord);
//thrid beat
rythmicPattern.play(2, ref outDevice, information, Globals.chordProgression.Bars[barNum].Chord);
//fourth beat
rythmicPattern.play(3, ref outDevice, information, Globals.chordProgression.Bars[barNum].Chord);
}
}
private void playPauseButton_Click(object sender, RoutedEventArgs e)
{
// test if the track is being played
if (isPlaying)
rythmicPattern.Pause();
else
// if it was already paused, playing back from where I stopped
rythmicPattern.PlayAfterPause(beatNumber);
}
Thank you for your help.
Greg
You must use threading where you can play the sound in another thread, so you can execute pause method
Check this link Multi-threading in .NET: Introduction and suggestions