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.
Related
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.
I have created a Windows Form Application having axWindowsMediaPlayer control. I haven't created a playlist on it, but I have stored my .mp4 files at a particular location. I pass the path to my next video at Media Ended state. For the first time, the player receives the correct path and play. But for the second video, I can only see a black screen although the player is receiving the correct path to play.
Here is my code for Media Ended State:
private void axWindowsMediaPlayer_PlayStateChange(object sender, AxWMPLib._WMPOCXEvents_PlayStateChangeEvent e)
{
if(e.newState == 8)
{
//Getting jumpTo of selected page
var selectedElementJumpToValue = MainContentAreaBl.GetSelectedElementValue(_currentId, "jumpTo");
if (selectedElementJumpToValue != null)
{
_currentId = selectedElementJumpToValue;
if (_currentId != "menu")
{
pagination.Text = MainContentAreaBl.GetPaginationText(_currentId);
LaunchPlayer(selectedElementJumpToValue);
}
else
{
this.Hide();
this.SendToBack();
menu.BringToFront();
}
}
}
}
private void LaunchPlayer(string id)
{
string selectedElementPageTypeValue = MainContentAreaBl.GetSelectedElementPageTypeValue(id);
var playerFile = Path.Combine(Common.ContentFolderPath, MainContentAreaBl.GetSelectedElementDataPathValue(id));
if (selectedElementPageTypeValue == "video")
{
InitialiseMediaPlayer();
axShockwaveFlash.Stop();
axShockwaveFlash.Visible = false;
if (File.Exists(playerFile))
{
axWindowsMediaPlayer.URL = playerFile;
}
}
else if (selectedElementPageTypeValue == "flash")
{
InitialiseShockwaveFlash();
axWindowsMediaPlayer.close();
axWindowsMediaPlayer.Visible = false;
if (File.Exists(playerFile))
{
axShockwaveFlash.Movie = playerFile;
axShockwaveFlash.Play();
}
}
}
private void InitialiseMediaPlayer()
{
axWindowsMediaPlayer.Visible = true;
axWindowsMediaPlayer.enableContextMenu = false
axWindowsMediaPlayer.uiMode = "none";
axWindowsMediaPlayer.Dock = DockStyle.Fill;
}
When I debugged my application, I saw Media Player getting the correct path after e.newState == 10 (Ready state). What am I doing wrong?
Edit 1: I found out that after my current video enters into Media Ended state, the player is stopped from playing. Even if I write axWindowsMediaPlayer.ctlControls.play();, it doesn't affect the media player. Is this a bug from in axWindowsMediaPlayer?
I have encountered this issue before as well. The most likely cause is that you are giving the command axWindowsMediaPlayer.ctlControls.play(); while the play state is still changing ( after Media Ended, it will change to Ready state). If a command is sent to the player while the play state is changing, it won't do anything. Another possible cause of your error is that sometimes Media State 9 (transitioning) needs to be included with if(e.newState == 8) such that you have if(e.newState == 8 | e.newState==9). I have had cases where it doesn't pick up on State 8 (media ending), possibly because it happens really fast and jumps to transitioning - not completely sure of this cause but I had a player that wasn't moving to the next video in the playlist because of this happening. To solve this I did something like:
if (e.newState == 8 | e.newState== 9 | e.newState== 10)
{
if (e.newState == 8)
{ //Insert your code here
}
This would vary slightly depending on what you are trying to achieve. Another thing to watch out for is using the PlayStateChange Event to set the Video URL, this causes problems as a result of re-entry problems with WMP - see other posts for further explanation on my last comment:
here is a good one and another here. Hope this helps!
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();
}
}
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);
}
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.