Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add audio programmatically to a Toast notification?

I had code like the following:

ToastNotifier ToastNotifier = ToastNotificationManager.CreateToastNotifier();
XmlDocument toastXml = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText02);
XmlNodeList toastNodeList = toastXml.GetElementsByTagName("text");
toastNodeList.Item(0).AppendChild(toastXml.CreateTextNode(title));
toastNodeList.Item(1).AppendChild(toastXml.CreateTextNode(stringContent));
XmlElement audio = toastXml.CreateElement("audio");
audio.SetAttribute("src", "ms-winsoundevent:Notification.Alarm7");
audio.SetAttribute("loop", "false");

However, testing this with:

toastXml.GetXml();

shows that the audio doesn't get added to the xml. How do I get it to be added. The docs for audio are here .

like image 280
ispiro Avatar asked Oct 20 '25 13:10

ispiro


1 Answers

if you're using Windows 10 we strongly recommend using the Notifications library. See the official documentation showing how to add audio to toasts.

Your code looks quite cleaner using the Notifications library

ToastContent toastContent = new ToastContent()
{
    Visual = new ToastVisual()
    {

    },

    Audio = new ToastAudio()
    {
        Src = new Uri("ms-appx:///Assets/Audio/CustomToastAudio.m4a")
    };
};

But if you prefer using the XML DOM manually, or have to target Windows 8, the mistake is that you never added the audio element. See the last line below.

XmlDocument toastXml = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText02);
...
XmlElement audio = toastXml.CreateElement("audio");
audio.SetAttribute("src", "ms-winsoundevent:Notification.Alarm7");
audio.SetAttribute("loop", "false");

// Add the audio element
toastXml.DocumentElement.AppendChild(audio);
like image 139
Andrew Leader Avatar answered Oct 23 '25 05:10

Andrew Leader



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!