ispiro
ispiro

Reputation: 27633

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 .

Upvotes: 4

Views: 967

Answers (1)

Andrew Leader
Andrew Leader

Reputation: 985

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);

Upvotes: 3

Related Questions