I am using MedialPlayer control to play sound effects in my app as explained here. Sounds are short sound effects that play "in the background" when something happens in the app, user should not see any sort of media playback control.
Code is fairly straight forward, looks something like this:
MediaPlayer mPlayer = new MediaPlayer();
mPlayer.Source = MediaSource.CreateFromUri(pathUri);
mPlayer.Play();
This works well, except, when user presses volume control button on the keyboard, a mini media player control appears next to volume control and the user can press play button to play the last sound again (see picture). I want to hide this. User should not see this or be able to replay sounds.
Solutions offered in question 14578867 do not work. Properties mentioned in the answers do not exist (e.g. IsPlayPauseVisible, uImode, IsInteractive). I tried using similar properties from SystemMediaTransportControls but it makes no difference. I think these are meant for the control that appears in the app (which I do not have), not for the "OS media control" that I want to hide.
mPlayer.SystemMediaTransportControls.IsEnabled = false;
mPlayer.SystemMediaTransportControls.IsPlayEnabled = false;
How can I disable/hide this?
Here is a step-by-step guide to replicate the issue:
Create a new Windows Universal Visual C# Blank App
Add a button to MainPage.xaml and mp3 file to assets
Paste below code to MainPage.cs
Run the app, click button
On the keyboard press volume up button
Observe the "media control" with play button next to volume control (see image above).
Pressing play button plays the sound again. If you are quick you can also pause the playback. SystemMediaTransportControls properties make no difference.
using Windows.Media.Core;
using Windows.Media.Playback;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Input;
namespace App2
{
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
}
private void Button_Tapped(object sender, TappedRoutedEventArgs e)
{
MediaPlayer mPlayer = new MediaPlayer();
mPlayer.Source = MediaSource.CreateFromUri(new System.Uri("ms-appx:///Assets/clap.mp3"));
mPlayer.SystemMediaTransportControls.IsPlayEnabled = false;
mPlayer.SystemMediaTransportControls.IsEnabled = false;
mPlayer.Play();
}
}
}
It seems it is caused by the MediaPlayer is not ready, when we set false to the MediaPlayer.SystemMediaTransportControls.IsPlayEnabled.
We should be able to add MediaOpened event of the MediaPlayer, then we can set false to the MediaPlayer.SystemMediaTransportControls.IsPlayEnabled in the MediaOpened event.
For example:
MediaPlayer mPlayer;
private void Button_Click(object sender, RoutedEventArgs e)
{
mPlayer = new MediaPlayer();
mPlayer.Source = MediaSource.CreateFromUri(new System.Uri("ms-appx:///Assets/xxxxx.mp3"));
mPlayer.MediaOpened += MPlayer_MediaOpened;
mPlayer.Play();
}
private void MPlayer_MediaOpened(MediaPlayer sender, object args)
{
mPlayer.SystemMediaTransportControls.IsEnabled = false;
}
If you just disable the button that in SystemMediaTransportControls, you should be able to set false to MediaPlayer.CommandManager.IsEnabled.
If you are using MediaPlayer to play media, you can get an instance of the SystemMediaTransportControls class by accessing the MediaPlayer.SystemMediaTransportControls property. If you are going to manually control the SMTC, you should disable the automatic integration provided by MediaPlayer by setting the CommandManager.IsEnabled property to false.+
If you disable the MediaPlaybackCommandManager of the MediaPlayer by setting IsEnabled to false, it will break the link between the MediaPlayer the TransportControls provided by the MediaPlayerElement, so the built-in transport controls will no longer automatically control the playback of the player. Instead, you must implement your own controls to control the MediaPlayer.
For more info, see Set up transport controls.
For example:
_mediaPlayer = new MediaPlayer();
_systemMediaTransportControls = _mediaPlayer.SystemMediaTransportControls;
_mediaPlayer.CommandManager.IsEnabled = false;
Related
I am trying to make like my own music app. With my dependency service solution in iOS i can hear the mp3 just fine but once I navigate through other pages the file stops. So my question is, how can I make so the file keeps playing even if i navigate through different pages after i "play" it?
This is my code:
My button where I pick the "track".
async void PlayThisSongButton (object s, EventArgs e)
{
DependencyService.Get<IPlayerVoice>().PlayAudioFile("myfilename.mp3");
}
Interface:
public interface IPlayerVoice
{
void PlayAudioFile(string fileName);
}
Dependency service iOS:
[assembly: Xamarin.Forms.Dependency(typeof (VoicePlayer_iOS))]
namespace myProject.iOS
{
public class VoicePlayer_iOS : IPlayerVoice
{
AVAudioPlayer player;
public VoicePlayer_iOS()
{
}
public void PlayAudioFile(string fileName)
{
string sFilePath = NSBundle.MainBundle.PathForResource
(Path.GetFileNameWithoutExtension(fileName), Path.GetExtension(fileName));
var url = NSUrl.FromString(sFilePath);
var _player = AVAudioPlayer.FromUrl(url);
_player.FinishedPlaying += (object sender, AVStatusEventArgs e) =>
{
_player = null;
};
_player.Play();
}
}
}
So with this current code. I click on my button where i start the audiofile. I then navigate to a different page. The audiofile stops. Any idea how i can solve this?
I have never worked with audio in Xamarin Forms but looked into it once.
I think the comment from #yanyankelevich with a GitHub link would still stop the audio when the user navigates away from the page.
As #yanyankelevich suggested though, using a background service might be your best bet. Some links for that (there is a lot of code so I will not duplicate it in this post):
iOS AVAudioPlayer (specifically check out the PlayBackgroundMusic method and the other background related methods below that one)
Android Background Audio Streaming
For a super simple way of doing it (which I do not suggest and have not ever tried), have you tried just running your method within a Device.BeginInvokeOnMainThread() which will do a fire and forget?
Device.BeginInvokeOnMainThread(() => DependencyService.Get<IPlayerVoice>().PlayAudioFile("myfilename.mp3"));
I would say you need to Use MVVM or MVC and run the music on the main view.
this will allow you to browse the app, while your music still plays.
basically have the Main view and create a grid that you place your "browserView"
in, add all the normal code you would use for the app to the viewmodel of the browser.
then add the code for the music to the viewmodel of the mainview.
Just make sure to add the functionality to pause the music.
Using the MediaElement control and MediaCapture class, I am trying to record microphone input and play audio at the same time.
As soon as I start recording, whatever track is playing mutes. I don't think it stops, because it continues playing after the recording has stopped. I have added hooks into several events on the MediaElement and none are being fired. For example, CurrentStateChanged, MediaEnded, MediaFailed etc.
Recording code:
public async void InitializeMediaCapture()
{
_mediaCaptureManager = new MediaCapture();
var settings = new MediaCaptureInitializationSettings();
settings.StreamingCaptureMode = StreamingCaptureMode.Audio;
settings.MediaCategory = MediaCategory.Other;
await _mediaCaptureManager.InitializeAsync(settings);
}
private async void CaptureAudio()
{
_recordStorageFile = await KnownFolders.VideosLibrary.CreateFileAsync(fileName, CreationCollisionOption.GenerateUniqueName);
var recordProfile = MediaEncodingProfile.CreateM4a(AudioEncodingQuality.Auto);
await _mediaCaptureManager.StartRecordToStorageFileAsync(recordProfile, this._recordStorageFile);
//audio playback stops on preceding line of code
}
I use .Play() on the MediaElement to play the audio, with the control in my XAML and the audio source set there.
<MediaElement x:Name="playbackElement"
Source="ms-appx:///Audio/Song.mp3"
AutoPlay="False" />
I have also tried playing the audio as BackgroundAudio, but that didn't work either. Any ideas?
1.Never set a MediaElement's Source in XAML, unless that XAML is on a page that you navigate to after asking the user for consent.
2.Check to see if background music is playing and then set the source (in code).
Note: If you set the source and then immediately call Play(), the Play() will have no affect since the MediaElement will still be in the "Opening" state, instead set "AutoPlay = true" (works from code)
Here's a Reference
I'm trying to embed a youtube video in a winforms application.
When I click I button, a new panel pops up with the video in it and it should play.
However, it doesn't. There's just a black box and nothing happens. Here's what the code looks like for that button:
private void module1_summary_nextpic_Click(object sender, EventArgs e)
{
activePanel.Visible = false;
activePanel = module1_content;
module1_content.Size = module1_panel.Size;
activePanel.Visible = true;
doc1.LoadMovie(0, "http://youtu.be/2Vb8dg_un-A");
doc1.Play();
}
any ideas as to why it's not showing/playing? i'm using vs2012.
edit: i've tried this solution here: https://stackoverflow.com/questions/17666243/calling-play-on-c-sharp-shockwave-component-doesnt-start-youtube-video-playba?rq=1 with no avail.
There is a problem with your link. Link should be like this:
http://www.youtube.com/v/2Vb8dg_un-A
That will make youtube video embbeded. Also, if you want to make it to autoplay just add &autoplay=1 at the end of the link.
I have a Windows application written in C#/.NET.
How can I play a specific sound when a button is clicked?
You could use:
System.Media.SoundPlayer player = new System.Media.SoundPlayer(#"c:\mywavfile.wav");
player.Play();
You can use SystemSound, for example, System.Media.SystemSounds.Asterisk.Play();.
For Windows Forms one way is to use the SoundPlayer
private void Button_Click(object sender, EventArgs e)
{
using (var soundPlayer = new SoundPlayer(#"c:\Windows\Media\chimes.wav")) {
soundPlayer.Play(); // can also use soundPlayer.PlaySync()
}
}
MSDN page
This will also work with WPF, but you have other options like using MediaPlayer MSDN page
Additional Information.
This is a bit high-level answer for applications which want to seamlessly fit into the Windows environment. Technical details of playing particular sound were provided in other answers. Besides that, always note these two points:
Use five standard system sounds in typical scenarios, i.e.
Asterisk - play when you want to highlight current event
Question - play with questions (system message box window plays this one)
Exclamation - play with excalamation icon (system message box window plays this one)
Beep (default system sound)
Critical stop ("Hand") - play with error (system message box window plays this one)
Methods of class System.Media.SystemSounds will play them for you.
Implement any other sounds as customizable by your users in Sound control panel
This way users can easily change or remove sounds from your application and you do not need to write any user interface for this – it is already there
Each user profile can override these sounds in own way
How-to:
Create sound profile of your application in the Windows Registry (Hint: no need of programming, just add the keys into installer of your application.)
In your application, read sound file path or DLL resource from your registry keys and play it. (How to play sounds you can see in other answers.)
Code bellow allows to play mp3-files and in-memory wave-files too
player.FileName = "123.mp3";
player.Play();
from http://alvas.net/alvas.audio,samples.aspx#sample6 or
Player pl = new Player();
byte[] arr = File.ReadAllBytes(#"in.wav");
pl.Play(arr);
from http://alvas.net/alvas.audio,samples.aspx#sample7
To play an Audio file in the Windows form using C# let's check simple example as follows :
1.Go Visual Studio(VS-2008/2010/2012) --> File Menu --> click New Project.
2.In the New Project --> click Windows Forms Application --> Give Name and then click OK.
A new "Windows Forms" project will opens.
3.Drag-and-Drop a Button control from the Toolbox to the Windows Form.
4.Double-click the button to create automatically the default Click event handler, and add the following code.
This code displays the File Open dialog box and passes the results to a method named "playSound" that you will create in the next step.
OpenFileDialog dialog = new OpenFileDialog();
dialog.Filter = "Audio Files (.wav)|*.wav";
if(dialog.ShowDialog() == DialogResult.OK)
{
string path = dialog.FileName;
playSound(path);
}
5.Add the following method code under the button1_Click event hander.
private void playSound(string path)
{
System.Media.SoundPlayer player = new System.Media.SoundPlayer();
player.SoundLocation = path;
player.Load();
player.Play();
}
6.Now let's run the application just by Pressing the F5 to run the code.
7.Click the button and select an audio file. After the file loads, the sound will play.
I hope this is useful example to beginners...
I think you must firstly add a .wav file to Resources. For example you have sound file named Sound.wav. After you added the Sound.wav file to Resources, you can use this code:
System.Media.SoundPlayer player = new System.Media.SoundPlayer(Properties.Resources.Sound);
player.Play();
This is another way to play sound.
I am using VSTS 2008 with C# to develop Silverlight application embedded in web page of an ASP.Net web application. I have embedded in XAML a MediaElement item. My question is, I want to embed the page a Silverlight media player, which could let end user to control the MediaElement item manually to -- play/pause/stop/rewind/forward. Are there any references samples?
thanks in advance,
George
EDIT1: add more accurate requirements,
Actually, I want to control play manually, which means I want to handle the player play/pause/stop/rewind/forward events and add my code for the event handlers to control the MediaElement and do something else.
EDIT2: My needs are, I want to play two overlapped video. Screen as background video and camera as foreground video (place at right bottom corner). Here is my modification of code, my current issue is, only background video is played, foreground right bottom video is never played. Does anyone have any ideas why?
BTW: my modified code and current work is based on http://www.codeplex.com/sl2videoplayer
http://www.yourfilehost.com/media.php?cat=other&file=sl2videoplayer_24325_new.zip
Here is a brief description of my major modified code,
mediaControls.xaml.cs
private MediaElement _media = null;
private MediaElement _camera = null;
public MediaElement Camera
{
set
{
_camera = value;
}
}
void btnPlay_Checked(object sender, RoutedEventArgs e)
{
_camera.Play();
_media.Play();
OnPlayClicked();
}
Page.xaml
<MediaElement HorizontalAlignment="Stretch" Margin="0,0,0,0" x:Name="mediaPlayer" Stretch="Uniform" VerticalAlignment="Stretch" AutoPlay="false"/>
<MediaElement Width="100" Height="100" x:Name="cameraPlayer" AutoPlay="false" HorizontalAlignment="Right" VerticalAlignment="Bottom"/>
Page.xaml.cs
cameraPlayer.Source = App.Current.Resources["c"] as Uri;
App.xaml.cs (Application_Startup function)
else if (item.Key.ToLower() == "c")
{
FormatUri(e.InitParams["c"].ToString(), "c", false);
}
default.html
<param name="initParams" value="cc=true,markers=true,markerpath=markers_movie21.xml,m=http://localhost/screen.wmv,c=http://localhost/camera.wmv" />
Oh baby have I got the media player for you: Sl2 Video Player. MSPL open sourced and awesome.
To add the ability to control the player pragmatically, add ScriptableMembers.
You'll see the registration statement already in the code:
HtmlPage.RegisterScriptableObject("Page", page);
Now look at an example ScriptableMember:
[ScriptableMember]
public void SeekPlayback(string time)
{
TimeSpan tsTime = TimeSpan.Parse(time);
mediaControls.Seek(tsTime);
}
already exists in the code. Add more methods to do what you want to have happen. Then you can call the methods from managed code in another SL player:
HtmlElement videoPlugin = HtmlPage.Document.GetElementById("VideoPlayer");
if (videoPlugin != null)
{
ScriptObject mediaPlayer = (ScriptObject)((ScriptObject)videoPlugin.GetProperty("Content")).GetProperty("Page");
mediaPlayer.Invoke("SeekPlayback", TimeSpan.FromSeconds(seconds).ToString());
}
or from javascript:
var sl = document.getElementById("VideoPlayer");
var content = sl.Content.Page;
content.SeekPlayback('55');
If they are two seperate xap packages, there will be no way for the two to communicate since Silverlight sandboxes both individually.
SL2videoplayer says it supports streaming video. But when I try giving a media services broadcast url (OnDemand and Live) to init param 'm' nothing showed up. In the init param example page also a remote wmv file being played is shown.
Also are there any known issues of using this with SL 3?