--- title: WebFM API slug: Web/API/WebFM_API tags: - WebFMAPI translation_of: Archive/B2G_OS/API/WebFM_API ---

{{ non-standard_header() }}

{{ B2GOnlyHeader2('installed') }}

Summary

The WebFM API provides access to the device FM radio. It allows turning the radio on/off and switching among radio stations. This API is available through the {{domxref("window.navigator.mozFMRadio","navigator.mozFMRadio")}} property which is a {{domxref("FMRadio")}} object.

Включение и выключение радио

Для того чтобы включить радио используйте метод {{domxref("FMRadio.enable()")}}, для выключения {{domxref("FMRadio.disable()")}}.

Перед включением радио следует проверить доступность антены, так как без нее встроенный радиомодуль не в состоянии поймать какую либо станцию. Информация о доступности антенны находится в свойстве {{domxref("FMRadio.antennaAvailable")}}. Как правило, в мобильных устройствах роль антены выполняют наушники (проводная гарнитура). Каждый раз когда пользователь подсоединяет или отсоединяет проводную гарнитуру WebFM API вызывает событие {{event("antennaavailablechange")}}.

To turn the radio on it's necessary to provide a frequency to listen. That frequency (in MHz) is a number pass to the {{domxref("FMRadio.enable()")}} method.

// Частота радиостанции в MHz
var frequency = 99.1;
var radio = navigator.mozFMRadio;

if (radio.antennaAvailable) {
  radio.enable(frequency);
} else {
  alert("Вам необходимо подсоединить гарнитуру");
}

radio.addEventListener('antennaavailablechange', function () {
  if (radio.antennaAvailable) {
    radio.enable(frequency);
  } else {
    radio.disable();
  }
})

Note: The audio is output through the normal audio channel available on the device.

Switching among frequency

Switching from on frequency to another can be done manually or automatically. In any case, the current radio frequency listened to by the built-in radio is always available with the {{domxref("FMRadio.frequency")}} property. That property is number representing the frequency in MHz.

Manual switch

The {{domxref("FMRadio.setFrequency()")}} method must be used to set a new frequency to listen. However, there are some constraints about the value that can be set. The method will return a {{domxref("DOMRequest")}} object to handle the success or error of the method call. The frequency must fulfill the following requirements:

var change = radio.setFrequency(frequency);

change.onerror = function () {
  var min = radio.frequencyLowerBound;
  var max = radio.frequencyUpperBound;
  console.warn('The frequency must be within the range [' + min + ',' + max + ']');
}

change.onsuccess = function () {
  console.log('The frequency has been set to ' + radio.frequency);
}

Автоматический поиск

WebFM API предоставляет удобный способ автоматического поиска радиоканалов. Для восходящего поиска используйте метод {{domxref("FMRadio.seekUp()")}}, а для низходящего, метод {{domxref("FMRadio.seekDown()")}}.

The WebFM API also provides a convinient way to seek radio channels automatically. To that end, we can use the {{domxref("FMRadio.seekUp()")}} (to find a radio channel on a higher frequency than the current one) and {{domxref("FMRadio.seekDown()")}} method. The former is used to find a radio channel with a higher frequency than the current one, and the latter for a radio channel with a lower frequency. Those methods return a {{domxref("DOMRequest")}} object to handle the success or error of each method call.

Both methods will circle back to higher or lower frequency once they reach the {{domxref("FMRadio.frequencyLowerBound","frequencyLowerBound")}} or {{domxref("FMRadio.frequencyUpperBound","frequencyUpperBound")}} values. When they find a new radio channel, they change the current frequency and fire a {{event("frequencychange")}} event.

It's not possible to seek twice at the same time (e.g. it's not possible to seek up and down at the same time), trying to do so, will result in an error. But if necessary it's possible to stop seeking by calling the {{domxref("FMRadio.cancelSeek()")}} method. This method will also return a {{domxref("DOMRequest")}} object.

var radio   = navigator.mozFMRadio;
var seeking = false;
var UP      = document.querySelector("button.up");
var DOWN    = document.querySelector("button.down");

// When the frequency change, the seek
// functions automatically stop to seek.
radio.onfrequencychange = function () {
  seeking = false;
}

function seek(direction) {
  var cancel, search;

  // If the radio is already seeking
  // we will cancel the current search.
  if (seeking) {
    var cancel = radio.cancelSeek();
    cancel.onsuccess = function () {
      seeking = false;

      // Once the radio no longer seek,
      // we can try to seek as expected
      seek(direction);
    }

  // Let's seek up
  } else if (direction === 'up') {
    // Just to be sure that the radio is turned on
    if (!radio.enabled) {
      radio.enable(radio.frequencyLowerBound);
    }
    search = radio.seekUp();

  // Let's seek up
  } else if (direction === 'down' {
    // Just to be sure that the radio is turned on
    if (!radio.enabled) {
      radio.enable(radio.frequencyUpperBound);
    }
    search = radio.seekDown();
  }

  if (search) {
    search.onsuccess = function () {
      // Ok, we are seeking now.
      seeking = true;
    };
    search.onerror = function () {
      // Something goes wrong... ok, let's try again.
      seek(direction);
    }
  }
}

UP.addEventListener('click', function () {
  seek('up');
});

DOWN.addEventListener('click', function () {
  seek('down');
});

Specification

Not part of any specification.

See also