Audio

WAudio is a widget to play audio. It is a low-level widget, mapping directly onto a <audio> element available in HTML5 compliant browsers.

In almost every situation you should use

  • the WMediaPlayer widget if you want the user to be able to interact with the audio, or
  • the WSound widget for simple sound feedback.

Usage of the audio element consists of adding one or more audio sources and setting some options.

Example
source
#include <Wt/WAudio.h>
#include <Wt/WContainerWidget.h>
#include <Wt/WLink.h>
#include <Wt/WText.h>


// Define media source locations.
std::string mp3Audio =
            "https://www.webtoolkit.eu/audio/LaSera-NeverComeAround.mp3";
std::string oggAudio =
            "https://www.webtoolkit.eu/audio/LaSera-NeverComeAround.ogg";

auto container(std::make_unique<Wt::WContainerWidget>());

Wt::WAudio *audio = container->addNew<Wt::WAudio>();
audio->addSource(Wt::WLink(mp3Audio));
audio->addSource(Wt::WLink(oggAudio));
audio->setOptions(Wt::PlayerOption::Controls);
audio->setAlternativeContent
  (std::make_unique<Wt::WText>("You don't have HTML5 audio support!"));

Wt::WText *out = container->addNew<Wt::WText>();

audio->playbackStarted().connect([=] {
        out->setText("<p>Audio playing</p>");
});

audio->playbackPaused().connect([=] {
        out->setText("<p>Audio paused</p>");
});

audio->ended().connect([=] {
        out->setText("<p>Audio ended</p>");
});

audio->volumeChanged().connect([=] {
        out->setText("<p>Volume changed</p>");
});

Use the method setAlternativeContent() to show alternative content if the audio cannot be played. The alternative content can be any widget; you can set it to an alternative media player (QuickTime, Flash, ...), show a Flash movie, an animated gif, a text, a poster image, ... . There are two reasons why the browser may use the alternative content:

  • either because the browser does not support the HTML5 audio tag (alternative content is displayed even when JavaScript is not available), or
  • because none of the specified sources contain an audio format that is understood by the browser (requires JavaScript to display the alternative content).

The addSource() and setAlternativeContent() may not be called after the widget is rendered.

Top