Play Sound in .NET MAUI with Plugin.Maui.Audio
ฝัง
- เผยแพร่เมื่อ 11 ก.ค. 2024
- If you need to play a small sound effect or just a song this plugin is for you! With Plugin.Maui.Audio it's very easy to just add one or multiple sounds to your application. Ideal for your audio feedback whenever the user taps on something or maybe you're building a game PEW PEW!
💝 Join this channel to get access to perks:
th-cam.com/channels/ral.html...
Disclaimer: this channel is done on personal title, in my free time, and not officially affiliated with or endorsed by Microsoft (my employer) in any way. Opinions and views are my own.
🛑 Don't forget to subscribe to my channel for more cool content: th-cam.com/users/GeraldVerslui...
🐦 Follow me on Twitter: / jfversluis
🤝 Join the Discord server: / discord
🔗 Links
Sample Code Repo: github.com/jfversluis/MauiPlu...
Plugin.Maui.Audio Repo: github.com/jfversluis/Plugin....
.NET MAUI Docs: docs.microsoft.com/dotnet/com...
⏱ Timestamps
00:00 - Play Sound in .NET MAUI
00:13 - What is Plugin.Maui.Audio?
01:10 - Add NuGet Package
01:54 - Use with Dependency Injection
03:26 - Implement Playing a Sound
06:04 - Explore AudioPlayer APIs
07:44 - Prevent Memory Leaks!
08:35 - Play a Sound The Easy Way
09:12 - Bring Your Ideas!
🎥 Video edited with Filmora
🙋♂️ Also find my...
Blog: blog.verslu.is
Twitch: / jfversluis
All the rest: jfversluis.dev
#dotnetmaui #sound #audio #dotnet6 #maui - วิทยาศาสตร์และเทคโนโลยี
I really appreciate how you always start from File New Project and show how everything needs to be setup.
Hey Donovan! Good seeing you here! 😄 thanks so much for the kind words
That is exactly what I needed. It works great.
Perfect, glad to hear it!
Thanks Gerald, great content. I'm already making use of this.
Oh that’s great, thanks! Let us know if you need anything
Sound was always very useful, nice to have a plugin for MAUI!
Let us know what you think of you decide to try it!
I think you're right. This seems much more appropriate to use. Thanks so much, dude!
Hi. Thanks for the great plugin. In the video you recommend disposing of the IAudioPlayer to protect against memory leaks. I'm attempting to do this but the Dispose can't be used after calling the Play method as the class is still in use and causes a COMException on Windows. I've tried to use the PlaybackEnded event to tidy up the resource but on Windows the sender is a Windows.Media.Playback.MediaPlayer object so I can't use this as it isn't platform independent. The EventArgs parameter has no information relating to the IAudioPlayer that has just completed. How do you recommend tidying up the resource once the play back is complete?
Great thanks. This works for MAUI hybrid as well. Much appreciated.
Great! Yeah most of the things out there should work in some way with Blazor Hybrid as well
Super helpful. Thanks @Gerald
Glad to hear that! Thanks!
That's great! it should be part of Microsoft.Maui.Media namespace. Thanks Gerald!
That would be awesome if that happened! Thanks Pierre!
@@jfversluis The API is clean , easy to use, and is implemented on all platforms. The only thing I see is that it is implicitly async (i.e. sounds play while async animations play) but it is not explicitly async (no await on the Play()) .
Meaning Play() has to be called before awaits and cannot be part of a Task.WhenAll.... not a big deal, but since it's async anyway.
Hm if that’s something you’d like to see changed or added, make sure to open an issue so we can discuss!
Great! Thaks!
thank u so much, now i can finish my assignmenmt!
Awesome! Good luck!
Thank you Gerald, nice tool. I am using it in a small app. I found that if you are going to use the player.Dispose() bit, you need to put in a delay first, otherwise you get an exception, i assume because its trying to discard the player while its still playing.
Ah that is valuable information! If you don't mind, could you see if there is an issue for that on the repo or open one with all the details you might have around this? Then we can have a look. Thank you!
when looping the sound there is short delay before the sound replays can i delete that and make the sound replays faster without delay?
Thanks for sharing this, however I'm surprised it's not in the main MAUI code as it's such an obvious thing to have.
Nice video, I am sure I will find a use for this.
Awesome! Good luck!
Great. It will replace my own implementation ! Good job 👍
Awesome! Let us know if you’re still missing something in comparison!
Great work Gerald! I assume I can use a "Using" block around the player instead of calling the Dispose method correct? Also, do you think there would be any benefits of keeping a reference to streams that are used repeatedly (i.e. every 10 seconds over a period of 2 hours) rather than executing FileSystem.OpenAppPackage...?
that's what I did. so far no leaks. I put it in a service that loads the good.wav, bad.wav, question.wav and put that into DI.
I made it a ObservableProperty in my viewModel, initilize it my page and just used the Play method on the viewModel. That fixed not getting the sound after a few times since I replayed it every few seconds since I'm making a BattleShip game and using the sounds for the attacks
Thanks for this it's really what I needed I think also you'll share the full music player where we can stream Audio in File Directory. Thanks!
Awesome video Gerald. Is it possible to use this plugin and stream real-time voice data like a push-to-talk walkie talkie? I know web-rtc and signal-r will come into play. Not sure if MAUI/MAUI Blazor has libraries/api's for this?
Thanks a lot Gerald! This is more than welcome!
I guess that it's possible to do it also from the code in the ViewModel, how would you do that in a clean way?
Absolutely! Check out the sample app we have in the plug-in repository that has a MVVM style sample
Hi Gerald I already learned some stuff with your videos and thank you for that! Can you make a video on how to change the notification sound on a
API above 26, I'm unable to make a custom sound to sound when the notification appears, I always get the default sound.
Finally, thank you!
Never understood how Xamarin supported audio and yet MAUI doesn't?
On Xamarin it's only supported through a plugin as well and that simply wasn't ported to .NET MAUI yet, now it is!
Maui is very exciting! I have a question; i want to have a background music on my app that will start right after the splash screen. Is there any way to do it now?
Very clear presented, thank you for creating such helpful functionality for cross platform apps ! Is there a widget also planned for this, to add UI control of audio files ?
Thank you! This is meant to be a non-visual control. I guess for a visual one you could look into MediaElement: th-cam.com/video/_sp4RG0I0x4/w-d-xo.html
Hey @Gerald Can we detect signal strength updating value in xamarin forms using Telephony manager because I didn't find any event in this library related to this
yo! Thanks for the video. I came here from your other video on recording sound in Xamarin Forms (uses Plugin.AudioRecorder package I think?)
I'm curious if that package works with MAUI apps.
Plugin.Maui.Audio now also records! Check the preview version
Great 👍
Thank you!
Can you make a tutorial about Bluetooth connections?
(I want to connect my smart watch to my application and read its data)
Great add on. Is there a way to declare it globally where I can turn it on with one button and stop & dispose with another button. If I declare in both buttons, it will work first time, but not the 2nd... it will start the 2nd time, but not stop the 2nd time.
Great work! What is the best way to use this plugin to play multiple audio files?
Create multiple players :)
Great video!! Will this also work on .Net Maui 7?
Absolutely
im a little confused on where we are supposed to put the player.Dispose(), when i put it in my playAudio method right after the player.Play() line i get a runtime error
Thanks! 🙏
❤🧡💛💚💙💜🤍
You’re welcome! My (Dutch?) friend!
@@jfversluis Danish! 🧀🧀
Aaah very good haha!
@@jfversluis I have a small issue with this, testing on windows, sounds play just fine, but on Android, it's like the end of the audio is cut short 🔜🔚
@@jfversluis When checking the value of IAudioPlayer.Duration, the precision are not identical campared we Windows and Android
var player = audioManager.CreatePlayer(await FileSystem.OpenAppPackageFileAsync("dswpnup.wav"));
var duration = player.Duration;
/*
player.Duration
Android: 0.532
Windows: 0.5328798
*/
Im creating a app for my familiy. Planning, calendar and more. It is Azure hosted grpc service, which uses streaming events for all users and mvvm databinding in front.
Very nice to see this.
I have 1 problem though, all my iOS input controls is unresponsive, but, android/windows works glitchy ok
Sounds great!
Gerald, I would like to implement this code in my ViewModel. My audio clip is Binding from a json file. Any tips on doing this. I have a list of birds and then clicking on one to play ots chirping sound.
Hello.... do I need methods like these to play notification sounds? for example, if an error occurs in the application, an error sound should be played. The same for a success sounds.
Regards
Jaime
That is exactly the kind of sound file I want to play.
Now I need a "sound file picker" that will also work on at least Windows / Android and hopefully IOS. Any samples that let me pick a sound and ... play a sound from a filename or path or however it has to be done? While I am overall highly experienced I have no exposure to Android / IOS coding so I can't just write my own platform code... I don't think.
There is a file picker already available in .NET MAUI :)
This video covers it for Xamarin.Forms but it should be largely the same for .NET MAUI th-cam.com/video/4gV9ZV61rn4/w-d-xo.html
so you created this plugin? I am wondering just curious how to do you create these types of plugins is c# is used or another programming language?
I did! I have a whole video about how to do it yourself, maybe that helps: th-cam.com/video/ZCQrlGT7MhI/w-d-xo.html
Thank you Gerald.. how can we record audio in .net maui, and if its not yet available when it it will be?
We're thinking about adding that here as well. No timeline yet, thanks!
Thanks very much for this code package (201 download). I am working on an app that requires sound and the ability to drag one object to another. Now I resolved sound issue need to resolved the drag issue. The DragGestureRecognizer takes too long to be recognized needs to implement something like swipe but dragging an object to any location on the screen. open for suggestion.
Thank you Gerald, is it possible play same audio in andirod auto. any references will be helpful.
Maybe this will help th-cam.com/video/nNkVxegb2oU/w-d-xo.html
👌
Thanks!
Any news around a video player? I need one now, and can't find any. Tx
Working on MediaElement in the .NET MAUI Community Toolkit. I’ll try to release an early preview video this week
great work gerald but how can we record audio using maui
We're working on that to include it in this project, but in the meantime: www.nuget.org/packages/Plugin.Maui.AudioRecorder there are some more others
Excellent, how do I play a selected file using the file picker
Use file picker, open the stream, use that with this plugin and voila!
selecctedFile.OpenReadAsync()
Hey, so I am a little confused as to why the method for the audio player needs to be async. Reason being is, well, what part of the code you showed us guarantees that the player will finish playing before it’s disposed? Y’know? The thing about async programming is it gives the compiler the ability to execute multiple lines of code simultaneously… I am worried that disposing the audio directly after it is played may be a race condition error waiting to happen
Typically you will want to play a sound as a result or play music even, it wouldn’t be great if that blocked the ui and you would have to wait for it to be finished.
@@jfversluis that’s a fair statement. Thanks for telling me
I made timer that plays sounds when round starts or breaks starts, but weirdly it does not play sounds every time. Can it be something wrong with sync? It seems to be totally random.
Hm interesting. If you could put it in a small reproduction sample and report it in the repository? Then we can have a look at what might be going on.
@@jfversluis I added you as collaborator for ETS-RT which is the app. For me it is just practice app. But I would like to have it working, as it is good for our training evenings in Brazilian Jiujitsu. Feel free to check what ever you find.... it might not be the most beautiful code. I am rather new to this :P
@@markoviitanen4441 Ah sorry for not being clear. I meant "we" as the .NET MAUI team. Unfortunately I can't look into private repositories like this. Sorry!
How could I use with a streaming of radio url?
Not possible with this right now. You can use MediaElement
Introducing MediaElement for .NET MAUI - Playing Video & Audio
th-cam.com/video/_sp4RG0I0x4/w-d-xo.html
Is there a possibility to play a sound using a title url
What is a title url?
It is possible to play mp3 sound from a url ? thanks
Unfortunately not yet!
For those getting file not found error on Android , please include to your csproj file to any ItemGroup
Thanks for sharing! That should be in your csproj for a new project by default though 🤔
Any way to play a video?
Hey, for me sound is not playing in iPhone, it only plays in simulators . What am I missing
Did you try the silent switch on the side?
yes, .wav working but try with mp3 - this format doesn't work
That depends on the underlaying platform and the formats supported by that
can play mp3 files?
Not working in case you want to play from url I have to download the file first 😢
Eu estou precisando criar um player que direciona o Playlist para a saída padrão e tem a opção de clicar em um áudio e enviar para um segunda saída, um segundo dispositivo, para isso preciso selecionar os dispositivos de e definir no player em qual quero que ele rode.
Sounds like a great and challenging project 😉
@@jfversluis THANK YOU
Good afternoon, why is it that when I press the button, it freezes and nothing happens??there is no music
Not sure, report an issue to the repo with a reproduction sample if you want us to take a look
thanks for the quick response, I found the problem, everything works
@fallout9285 perfect!
@@jfversluis hello again, when I created another page and registered everything the same way, another error occurs,
Severity Code Description Project File String Suppression Status
Error CS7036 There is no argument corresponding to the required parameter "AudioManager" from "StartPage.StartPage(IAudioManager)". MauiApp1 (net7.0-android), MauiApp1 (net7.0-ios), MauiApp1 (net7.0-mac catalyst), MauiApp1 (net7.0-windows10.0.19041.0) C:\Users\Fallout\source
epos\Path\MauiApp1\MauiApp1\App.xaml.cs 11 Active
How do you record audio on a maui app?
We’re planning on adding that soon
@@jfversluis you mean .net maui does not have that ability yet?
And also can this still be implemented using platform specific code in my maui app?
@@shahanahmed9444 .NET MAUI absolutely does, if I can create a plugin for it, you can implement the code to do it yourself. But there is currently no plugin for you to use.
@@jfversluis thats awesome, dude. If I wanted to create my own plugins, for example, for accessing the microphone to record audio, how would i go about doing so? Can you point me in the right direction so that i can also learn how to implement plugins to access native features on android and ios which i cannot do so on maui out of the box?
Error when using builder.Services.AddSingleton(AudioManager.Current) the AudioManager does not exist
You’re going to have to add the right using statement or fully qualify the type with Plugin.Maui.Audio.AudioManager
@@jfversluis Thanks, did see that in your code
If someone going to use this on another page other than the main page, you should write the navigation method like this:
await Navigation.PushAsync(new OtherPage(AudioManager.Current));
i delete mainpage. i replace it with bmiview. where should i wrote this code? tnx
@@datisa99 wherever your going to navigate through pages.
Thank you, you saved my life!