aboutsummaryrefslogtreecommitdiff
path: root/files/ru/web/api/webfm_api/index.html
blob: 11727674af5bc4f29b2c6fd145e4310733116dc5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
---
title: WebFM API
slug: Web/API/WebFM_API
tags:
  - WebFMAPI
translation_of: Archive/B2G_OS/API/WebFM_API
---
<p>{{ non-standard_header() }}</p>

<p>{{ B2GOnlyHeader2('installed') }}</p>

<h2 id="Summary">Summary</h2>

<p>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.</p>

<h2 id="Включение_и_выключение_радио">Включение и выключение радио</h2>

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

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

<p>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.</p>

<pre class="brush: js">// Частота радиостанции в 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();
  }
})
</pre>

<div class="note">
<p><strong>Note:</strong> The audio is output through the <code>normal</code> audio channel available on the device.</p>
</div>

<h2 id="Switching_among_frequency">Switching among frequency</h2>

<p>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 <a href="http://en.wikipedia.org/wiki/Hertz" title="http://en.wikipedia.org/wiki/Hertz">MHz</a>.</p>

<h3 id="Manual_switch">Manual switch</h3>

<p>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:</p>

<ul>
 <li>The frequency must be in the range defined by {{domxref("FMRadio.frequencyLowerBound")}} and {{domxref("FMRadio.frequencyUpperBound")}}. If the frequency is out of range, it will result in an error.</li>
 <li>The frequency must be stepped based on the value of {{domxref("FMRadio.channelWidth")}}. If it's not the case, the frequency will be rounded accordingly. For example, if 100MHz is a valid frequency and if {{domxref("FMRadio.channelWidth","channelWidth")}} has the value 0.2, trying to set a frequency of 100.15 will result in a frequency set to 100.2.</li>
</ul>

<pre class="brush: js">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);
}
</pre>

<h3 id="Автоматический_поиск">Автоматический поиск</h3>

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

<p>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.</p>

<p>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.</p>

<p>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.</p>

<pre class="brush: js">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');
});
</pre>

<h2 id="Specification">Specification</h2>

<p>Not part of any specification.</p>

<h2 id="See_also">See also</h2>

<ul>
 <li>{{domxref("FMRadio")}}</li>
 <li><a href="https://github.com/mozilla-b2g/gaia/tree/master/apps/fm" title="https://github.com/mozilla-b2g/gaia/tree/master/apps/fm">The FM app on Gaïa</a></li>
</ul>