Windows Media Player ctlcontrols.play and URL don't work - c#

private void mediaPlayer_Enter()
{
string path = Path.GetFullPath(currentTrack.Text);
System.Diagnostics.Debug.WriteLine(path);
mediaPlayer.URL = path;
mediaPlayer.Ctlcontrols.play();
}
This is the piece of code which is being called when the state of the media player turns to "media ended". I know that it does execute that line of code but it still doesn't play. It takes the item out of the listbox (which is the playlist) and loads it into the mediaPlayer but does not Automatically play the song. I have to press the button to start playing it - it has do play it stright away by itself. What am I doing wrong?

I believe this will autoplay your media:
http://msdn.microsoft.com/en-us/library/windows/desktop/dd562405(v=vs.85).aspx
If the AxWindowsMediaPlayer.settings.autoStart property is true, playback begins automatically whenever you set currentMedia.

In the PlayStateChange Event or use your logic, the player must be ready for playing the file before we use the Play() command.
private void WMPlayer1_PlayStateChange(object sender,AxWMPLib._WMPOCXEvents_PlayStateChangeEvent e)
{
if (WMPlayer1.playState == WMPPlayState.wmppsReady)
{
WMPlayer1.Ctlcontrols.play();
}
}

Related

C# repeating a mp3 file once it has finished

In my current project, i have music that plays depending on the gamestate. Like most games, once the soundtrack ends it then repeats. I'd like to implement such feature into my game so it automatically plays however i'm uncertain where i'd start.
The code/algorithm must acknowledge the fact that the soundtrack has ended and repeat baring in mind that it also will have more code connected to it once i create the gamesettings and sounds sub menu where the user is able to change the sounds etc. This is what i have so far:
static public WindowsMediaPlayer Introthemetune = new WindowsMediaPlayer();
public LaunchScreen()
{
this.Opacity = 0;
InitializeComponent();
Introthemetune.URL = "Finalised Game Soundtrack.mp3";
}
You can do this in two ways,
1. Subscribe to PlayStateChange Event
You would need to subscribe to PlayStateChange event and check the NewState
Introthemetune.PlayStateChange += Introthemetune_PlayStateChange;
private void Introthemetune_PlayStateChange(object sender, AxWMPLib._WMPOCXEvents_PlayStateChangeEvent e)
{
if(e.newState == 8)
{
// Play Again
}
}
You can read more on the different play states here
2. Set Loop Mode.
The most easiest approach would be to set the loop mode.
Introthemetune.settings.setMode("loop", true);
Introthemetune.URL = "Finalised Game Soundtrack.mp3";
This would ensure the track is played repeated continuously.

How can I play a sound with defined start- and end-time in .Net

In my C# project I want to play a sound with a specified start- and end time.
I used the System.Media.SoundPlayer with the .Play() function. But with this function I can only play the whole sound file or can abort it after I have counted the runtime.
In fact I want to say, that the given sound file should start for example at time 1m:25s:30ms and should end at time 1m:50s:00ms or after a duration of 10s or so.
Does anybody know a simple solution for his problem?
Thanks 4 help.
Not really an answer, but this question got me wondering if you can do something like this:
long startPositionInBytes = 512;
long endPositionInBytes = 2048;
using ( var audioStream = File.OpenRead(#"audio.wav") )
{
audioStream.Position = startPositionInBytes;
using ( var player = new SoundPlayer(audioStream) )
{
player.Play();
do
{
Thread.Sleep(1);
} while ( audioStream.Position <= endPositionInBytes );
player.Stop();
}
}
In case you want to play a Background Media Player (for e.g., an audio file) which would start from a specific time and would work for a certain duration, then this code snippet could also be useful:
StorageFile mediaFile = await KnownFolders.VideosLibrary.GetFileAsync(fileName);//the path
BackgroundMediaPlayer.Current.SetFileSource(mediaFile);
BackgroundMediaPlayer.Current.Position = TimeSpan.FromMilliseconds(3000/*enter the start time here*/);
BackgroundMediaPlayer.Current.Play();
await Task.Delay(TimeSpan.FromMilliseconds(10000/*for how long you want to play*/));
BackgroundMediaPlayer.Shutdown();//stops the player
**But this would only work for Windows 8.1 and above.
For more information, click here...
In the End I use the NAudio library. That can handle this - not in a perfect way but ok.
see https://stackoverflow.com/a/13372540/2936206
I got it to work by using Windows Media Player in a C sharp program with a timer control and an open dialog.
I followed a sample that used buttons on the form and made the media player invisible.
After opening the file with an Open button that used the open dialog to open the mp3 file, on the Play button I put this code [the end effect is that it started the file in position 28.00 and ended it in position 32.50]:
private void button2_Click(object sender, EventArgs e)
{
axWindowsMediaPlayer1.URL = openFileDialog1.FileName;
timer1.Start();
axWindowsMediaPlayer1.Ctlcontrols.currentPosition = 28.00;
axWindowsMediaPlayer1.Ctlcontrols.play();
}
Then in the timer tick event:
private void timer1_Tick(object sender, EventArgs e)
{
if (axWindowsMediaPlayer1.Ctlcontrols.currentPosition >= 32.50)
{ axWindowsMediaPlayer1.Ctlcontrols.pause(); }
label1.Text = String.Format("{0:0.00}",
axWindowsMediaPlayer1.Ctlcontrols.currentPosition);
}

Pause/Play MP3 file in C# using WMP

I am once again a bit stuck in my practising.
I want an MP3 file to play when i open my program - I can do that, i got music.
I also want a checkbox which allows to pause the music - But either I'm very tired, or the thing won't work - Nothing happens when i check/uncheck it. I've done it like this:
public void PlayPause(int Status)
{
WMPLib.WindowsMediaPlayer wmp = new WMPLib.WindowsMediaPlayer();
switch (Status)
{
case 0:
wmp.URL = "Musik.mp3";
break;
case 1:
wmp.controls.play();
break;
case 2:
wmp.controls.pause();
break;
}
}
Upon opening the program, the method is called with case 0. Music plays. All good.
However this doesn't work, and i don't get why, as it is pretty simple code.
public void checkBox1_CheckedChanged(object sender, EventArgs e)
{
if (checkBox1.Checked == true)
{
PlayPause(2);
}
else if (checkBox1.Checked == false)
{
PlayPause(1);
}
}
Any idea as to why checking the checkbox doesn't pause/unpause the music?
You're instantiating a completely new WindowsMediaPlayer object each time you call that PlayPause function.
Thus, when you call pause later on, you're pausing nothing.
You need to hold or pass a reference to that WMP object around, so that you're operating on the same one.
Well it's because you are creating a new media player every time you call PlayPause. Create it in the constructor and it should be fine.

Playing multiple sounds using muliple buttons

How to make multiple buttons play different sounds one at a time and have a common stop button using Windows Phone XNA framework? When a sound is played, it should play looped until one hits the stop button or hits another button.
The way I used SoundEffect with CreateInstance, it looped and played fine but when a second button is clicked, the second sound starts playing along with the first. Also need help with creating the common stop button. Thanks a lot in advance.
I was trying something like below for each button.
private void button2_Click(object sender, RoutedEventArgs e)
{
var stream = TitleContainer.OpenStream("Sounds/A3.wav");
var effect = SoundEffect.FromStream(stream);
SoundEffectInstance instance = effect.CreateInstance();
instance.IsLooped = true;
instance.Play();
But since the instance created isn't on a program-wide level, I'm having trouble creating a common stop button.
I'm a beginner in programming. Thank you for your understanding.
You can add a member variable to your class and some helper methods:
public class YourClass
{
private SoundEffectInstance currentSoundEffect = null;
private void StopCurrentSoundEffect()
{
this.currentSoundEffect.Stop();
this.currentSoundEffect = null;
}
private void PlaySoundEffect(string fileName)
{
this.StopCurrentSoundEffect();
using (var stream = TitleContainer.OpenStream("Sounds/A3.wav"))
{
var soundEffect = SoundEffect.FromStream(stream);
this.currentSoundEffect = soundEffect.CreateInstance();
this.currentSoundEffect.IsLooped = true;
this.currentSoundEffect.Play();
}
}
}
Now, each of your event handlers can just call this.PlaySoundEffect with the desired file name.

Stopping a SoundPlayer loop at the local level

I'm working on setting up an alarm that pops up as a dialog with multiple sound file options the user can choose from. The problem I'm having is creating a sound player at the local level that I can close with a button. The problem I'm having is that the sound keeps looping when I close the form because the SoundPlayer doesn't exist within the button click event.
here's what I have:
void callsound()
{
if (SoundToggle == 0) // if sound enabled
{
if ((SoundFile == 0) && (File.Exists(#"attention.wav")))
{
System.Media.SoundPlayer alarm = new System.Media.SoundPlayer(#"attention.wav");
alarm.PlayLooping();
}
if ((SoundFile == 1) && (File.Exists(#"aahh.wav")))
{
System.Media.SoundPlayer alarm = new System.Media.SoundPlayer(#"aahh.wav");
alarm.PlayLooping();
}
}
private void button1_Click(object sender, EventArgs e)
{
//alarm.Stop(); Only works if SoundPlayer declared at class level
this.Close();
}
Is there a way I can do what I want to do by declaring the SoundPlayer instances where I am? Or is there a way to declare it at the class level, and still be able to change the sound file based on user settings?
Why is this a problem? SoundPlayer doesn't support playing more than one sound at the same time anyway. Move it to class scope, override OnFormClosing event, problem solved.
public partial class Form1 : Form {
private System.Media.SoundPlayer alarm;
protected override void OnFormClosing(CancelEventArgs e) {
if (alarm != null) alarm.Stop();
}
}
You can try:
SoundMixer.stopAll();
or
SoundMixer.soundTransform = new SoundTransform(0);
The SoundMixer class controls global sound, so it should stop everything in the same security sandbox.
Using Powershell, I was playing with playing .wav files and started a repeating loop using the following:
$Playwav = new-object ('Media.SoundPlayer') $playpath1
$Playwav.PlayLooping()
I stopped the loop inside Powershell IDE by Run Section (F8):
$Playwav = new-object ('Media.SoundPlayer') $playpath1
$Playwav.PlayLooping()
$Playwav.stop()
FWIW, the .wav in my example was FPS Doug takethatbitch.wav. So the runaway loop made me laugh.
Hope this helps.

Categories