• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Audio Playback Development
2
3## When to Use
4
5You can use audio playback APIs to convert audio data into audible analog signals, play the signals using output devices, and manage playback tasks.
6
7**Figure 1** Playback status
8
9![en-us_image_audio_state_machine](figures/en-us_image_audio_state_machine.png)
10
11
12
13**Figure 2** Layer 0 diagram of audio playback
14
15![en-us_image_audio_player](figures/en-us_image_audio_player.png)
16
17## How to Develop
18
19For details about the APIs, see [AudioPlayer in the Media API](../reference/apis/js-apis-media.md).
20
21### Full-Process Scenario
22
23The full audio playback process includes creating an instance, setting the URI, playing audio, seeking to the playback position, setting the volume, pausing playback, obtaining track information, stopping playback, resetting the player, and releasing resources.
24
25For details about the **src** types supported by **AudioPlayer**, see the [src attribute](../reference/apis/js-apis-media.md#audioplayer_attributes).
26
27```js
28import media from '@ohos.multimedia.media'
29import fileIO from '@ohos.fileio'
30
31// Print the stream track information.
32function printfDescription(obj) {
33    for (let item in obj) {
34        let property = obj[item];
35        console.info('audio key is ' + item);
36        console.info('audio value is ' + property);
37    }
38}
39
40// Set the player callbacks.
41function setCallBack(audioPlayer) {
42    audioPlayer.on('dataLoad', () => { // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully.
43        console.info('audio set source success');
44        audioPlayer.play(); // The play() API can be invoked only after the 'dataLoad' event callback is complete. The 'play' event callback is then triggered.
45    });
46    audioPlayer.on('play', () => { // Set the 'play' event callback.
47        console.info('audio play success');
48        audioPlayer.pause(); // Trigger the 'pause' event callback and pause the playback.
49    });
50    audioPlayer.on('pause', () => { // Set the 'pause' event callback.
51        console.info('audio pause success');
52        audioPlayer.seek(5000); // Trigger the 'timeUpdate' event callback, and seek to 5000 ms for playback.
53    });
54    audioPlayer.on('stop', () => { // Set the 'stop' event callback.
55        console.info('audio stop success');
56        audioPlayer.reset(); // Trigger the 'reset' event callback, and reconfigure the src attribute to switch to the next song.
57    });
58    audioPlayer.on('reset', () => { // Set the 'reset' event callback.
59        console.info('audio reset success');
60        audioPlayer.release(); // Release the AudioPlayer instance.
61        audioPlayer = undefined;
62    });
63    audioPlayer.on('timeUpdate', (seekDoneTime) => { // Set the 'timeUpdate' event callback.
64        if (typeof(seekDoneTime) == 'undefined') {
65            console.info('audio seek fail');
66            return;
67        }
68        console.info('audio seek success, and seek time is ' + seekDoneTime);
69        audioPlayer.setVolume(0.5); // Trigger the 'volumeChange' event callback.
70    });
71    audioPlayer.on('volumeChange', () => { // Set the 'volumeChange' event callback.
72        console.info('audio volumeChange success');
73        audioPlayer.getTrackDescription((error, arrlist) => { // Obtain the audio track information in callback mode.
74            if (typeof (arrlist) != 'undefined') {
75                for (let i = 0; i < arrlist.length; i++) {
76                    printfDescription(arrlist[i]);
77                }
78            } else {
79                console.log(`audio getTrackDescription fail, error:${error.message}`);
80            }
81            audioPlayer.stop(); // Trigger the 'stop' event callback to stop the playback.
82        });
83    });
84    audioPlayer.on('finish', () => { // Set the 'finish' event callback, which is triggered when the playback is complete.
85        console.info('audio play finish');
86    });
87    audioPlayer.on('error', (error) => { // Set the 'error' event callback.
88        console.info(`audio error called, errName is ${error.name}`);
89        console.info(`audio error called, errCode is ${error.code}`);
90        console.info(`audio error called, errMessage is ${error.message}`);
91    });
92}
93
94async function audioPlayerDemo() {
95    // 1. Create an AudioPlayer instance.
96    let audioPlayer = media.createAudioPlayer();
97    setCallBack(audioPlayer); // Set the event callbacks.
98    // 2. Set the URI of the audio file.
99    let fdPath = 'fd://'
100    // The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\01.mp3 /data/app/el1/bundle/public/ohos.acts.multimedia.audio.audioplayer/ohos.acts.multimedia.audio.audioplayer/assets/entry/resources/rawfile" command.
101    let path = '/data/app/el1/bundle/public/ohos.acts.multimedia.audio.audioplayer/ohos.acts.multimedia.audio.audioplayer/assets/entry/resources/rawfile/01.mp3';
102    await fileIO.open(path).then((fdNumber) => {
103        fdPath = fdPath + '' + fdNumber;
104        console.info('open fd success fd is' + fdPath);
105    }, (err) => {
106        console.info('open fd failed err is' + err);
107    }).catch((err) => {
108        console.info('open fd failed err is' + err);
109    });
110    audioPlayer.src = fdPath; // Set the src attribute and trigger the 'dataLoad' event callback.
111}
112```
113
114### Normal Playback Scenario
115
116```js
117import media from '@ohos.multimedia.media'
118import fileIO from '@ohos.fileio'
119export class AudioDemo {
120  // Set the player callbacks.
121  setCallBack(audioPlayer) {
122    audioPlayer.on('dataLoad', () => { // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully.
123      console.info('audio set source success');
124      audioPlayer.play(); // Call the play() API to start the playback and trigger the 'play' event callback.
125    });
126    audioPlayer.on('play', () => { // Set the 'play' event callback.
127      console.info('audio play success');
128    });
129    audioPlayer.on('finish', () => { // Set the 'finish' event callback, which is triggered when the playback is complete.
130      console.info('audio play finish');
131      audioPlayer.release(); // Release the AudioPlayer instance.
132      audioPlayer = undefined;
133    });
134  }
135
136  async audioPlayerDemo() {
137    let audioPlayer = media.createAudioPlayer(); // Create an AudioPlayer instance.
138    this.setCallBack(audioPlayer); // Set the event callbacks.
139    let fdPath = 'fd://'
140    // The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\01.mp3 /data/app/el1/bundle/public/ohos.acts.multimedia.audio.audioplayer/ohos.acts.multimedia.audio.audioplayer/assets/entry/resources/rawfile" command.
141    let path = '/data/app/el1/bundle/public/ohos.acts.multimedia.audio.audioplayer/ohos.acts.multimedia.audio.audioplayer/assets/entry/resources/rawfile/01.mp3';
142    await fileIO.open(path).then((fdNumber) => {
143      fdPath = fdPath + '' + fdNumber;
144      console.info('open fd success fd is' + fdPath);
145    }, (err) => {
146      console.info('open fd failed err is' + err);
147    }).catch((err) => {
148      console.info('open fd failed err is' + err);
149    });
150    audioPlayer.src = fdPath; // Set the src attribute and trigger the 'dataLoad' event callback.
151  }
152}
153```
154
155### Switching to the Next Song
156
157```js
158import media from '@ohos.multimedia.media'
159import fileIO from '@ohos.fileio'
160export class AudioDemo {
161// Set the player callbacks.
162  private isNextMusic = false;
163  setCallBack(audioPlayer) {
164    audioPlayer.on('dataLoad', () => { // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully.
165      console.info('audio set source success');
166      audioPlayer.play(); // Call the play() API to start the playback and trigger the 'play' event callback.
167    });
168    audioPlayer.on('play', () => { // Set the 'play' event callback.
169      console.info('audio play success');
170      audioPlayer.reset(); // Call the reset() API and trigger the 'reset' event callback.
171    });
172    audioPlayer.on('reset', () => { // Set the 'reset' event callback.
173      console.info('audio play success');
174      if (!this.isNextMusic) { // When isNextMusic is false, changing songs is implemented.
175        this.nextMusic(audioPlayer); // Changing songs is implemented.
176      } else {
177        audioPlayer.release(); // Release the AudioPlayer instance.
178        audioPlayer = undefined;
179      }
180    });
181  }
182
183  async nextMusic(audioPlayer) {
184    this.isNextMusic = true;
185    let nextFdPath = 'fd://'
186    // The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\02.mp3 /data/app/el1/bundle/public/ohos.acts.multimedia.audio.audioplayer/ohos.acts.multimedia.audio.audioplayer/assets/entry/resources/rawfile" command.
187    let nextpath = '/data/app/el1/bundle/public/ohos.acts.multimedia.audio.audioplayer/ohos.acts.multimedia.audio.audioplayer/assets/entry/resources/rawfile/02.mp3';
188    await fileIO.open(nextpath).then((fdNumber) => {
189      nextFdPath = nextFdPath + '' + fdNumber;
190      console.info('open fd success fd is' + nextFdPath);
191    }, (err) => {
192      console.info('open fd failed err is' + err);
193    }).catch((err) => {
194      console.info('open fd failed err is' + err);
195    });
196    audioPlayer.src = nextFdPath; // Set the src attribute and trigger the 'dataLoad' event callback.
197  }
198
199  async audioPlayerDemo() {
200    let audioPlayer = media.createAudioPlayer(); // Create an AudioPlayer instance.
201    this.setCallBack(audioPlayer); // Set the event callbacks.
202    let fdPath = 'fd://'
203    // The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\01.mp3 /data/app/el1/bundle/public/ohos.acts.multimedia.audio.audioplayer/ohos.acts.multimedia.audio.audioplayer/assets/entry/resources/rawfile" command.
204    let path = '/data/app/el1/bundle/public/ohos.acts.multimedia.audio.audioplayer/ohos.acts.multimedia.audio.audioplayer/assets/entry/resources/rawfile/01.mp3';
205    await fileIO.open(path).then((fdNumber) => {
206      fdPath = fdPath + '' + fdNumber;
207      console.info('open fd success fd is' + fdPath);
208    }, (err) => {
209      console.info('open fd failed err is' + err);
210    }).catch((err) => {
211      console.info('open fd failed err is' + err);
212    });
213    audioPlayer.src = fdPath; // Set the src attribute and trigger the 'dataLoad' event callback.
214  }
215}
216```
217
218### Looping a Song
219
220```js
221import media from '@ohos.multimedia.media'
222import fileIO from '@ohos.fileio'
223export class AudioDemo {
224  // Set the player callbacks.
225  setCallBack(audioPlayer) {
226    audioPlayer.on('dataLoad', () => { // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully.
227      console.info('audio set source success');
228      audioPlayer.loop = true; // Set the loop playback attribute.
229      audioPlayer.play(); // Call the play() API to start the playback and trigger the 'play' event callback.
230    });
231    audioPlayer.on('play', () => { // Set the 'play' event callback to start loop playback.
232      console.info('audio play success');
233    });
234  }
235
236  async audioPlayerDemo() {
237    let audioPlayer = media.createAudioPlayer(); // Create an AudioPlayer instance.
238    this.setCallBack(audioPlayer); // Set the event callbacks.
239    let fdPath = 'fd://'
240    // The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\01.mp3 /data/app/el1/bundle/public/ohos.acts.multimedia.audio.audioplayer/ohos.acts.multimedia.audio.audioplayer/assets/entry/resources/rawfile" command.
241    let path = '/data/app/el1/bundle/public/ohos.acts.multimedia.audio.audioplayer/ohos.acts.multimedia.audio.audioplayer/assets/entry/resources/rawfile/01.mp3';
242    await fileIO.open(path).then((fdNumber) => {
243      fdPath = fdPath + '' + fdNumber;
244      console.info('open fd success fd is' + fdPath);
245    }, (err) => {
246      console.info('open fd failed err is' + err);
247    }).catch((err) => {
248      console.info('open fd failed err is' + err);
249    });
250    audioPlayer.src = fdPath; // Set the src attribute and trigger the 'dataLoad' event callback.
251  }
252}
253```
254