简体   繁体   中英

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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM