audio-playback.md 11.1 KB
Newer Older
W
wusongqing 已提交
1
# Audio Playback Development
W
wusongqing 已提交
2

W
wusongqing 已提交
3
## When to Use
W
wusongqing 已提交
4

W
wusongqing 已提交
5
You can use audio playback APIs to convert audio data into audible analog signals, play the signals using output devices, and manage playback tasks.
W
wusongqing 已提交
6

W
wusongqing 已提交
7
**Figure 1** Playback status
W
wusongqing 已提交
8

W
wusongqing 已提交
9 10 11 12 13 14 15
![en-us_image_audio_state_machine](figures/en-us_image_audio_state_machine.png)



**Figure 2** Layer 0 diagram of audio playback

![en-us_image_audio_player](figures/en-us_image_audio_player.png)
W
wusongqing 已提交
16 17 18 19 20 21 22

## How to Develop

For details about the APIs used for audio playback, see [js-apis-media.md](../reference/apis/js-apis-media.md).

### Full-Process Scenario

W
wusongqing 已提交
23
The 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.
W
wusongqing 已提交
24

W
wusongqing 已提交
25
For details about the **src** media source input types supported by **AudioPlayer**, see the [src attribute](../reference/apis/js-apis-media.md#audioplayer_attributes).
W
wusongqing 已提交
26 27

```js
W
wusongqing 已提交
28 29 30
import media from '@ohos.multimedia.media'
import fileIO from '@ohos.fileio'

W
wusongqing 已提交
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
function SetCallBack(audioPlayer) {
    audioPlayer.on('dataLoad', () => {              // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully.
        console.info('audio set source success');
        // The playback page is ready. You can click the Play button to start the playback.
    });
    audioPlayer.on('play', () => {                  // Set the 'play' event callback.
        console.info('audio play success');
        // The Play button is changed to the pausable state.
    });
    audioPlayer.on('pause', () => {                 // Set the 'pause' event callback.
        console.info('audio pause success');
        // The Play button is changed to the playable state.
    });
    audioPlayer.on('stop', () => {                  // Set the 'stop' event callback.
        console.info('audio stop success');
        // The playback stops, the playback progress bar returns to 0, and the Play button is changed to the playable state.
    });
    audioPlayer.on('reset', () => {                 // Set the 'reset' event callback.
        console.info('audio reset success');
        // You can reconfigure the src attribute to play another audio file.
    });
    audioPlayer.on('timeUpdate', (seekDoneTime) => {// Set the 'timeUpdate' event callback.
        if (typeof(seekDoneTime) == 'undefined') {
            console.info('audio seek fail');
M
mamingshuai 已提交
55 56
            return;
        }
W
wusongqing 已提交
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
        console.info('audio seek success, and seek time is ' + seekDoneTime);
        // The playback progress bar is updated to the seek position.
    });
    audioPlayer.on('volumeChange', () => {          // Set the 'volumeChange' event callback.
        console.info('audio volumeChange success');
        // Display the updated volume.
    });
    audioPlayer.on('finish', () => {                // Set the 'finish' event callback, which is triggered when the playback is complete.
        console.info('audio play finish');
    });
    audioPlayer.on('error', (error) => {            // Set the 'error' event callback.
        console.info(`audio error called, errName is ${error.name}`);
        console.info(`audio error called, errCode is ${error.code}`);
        console.info(`audio error called, errMessage is ${error.message}`);
    });
}

function printfDescription(obj) {
    for (let item in obj) {
        let property = obj[item];
        console.info('audio key is ' + item);
        console.info('audio value is ' + property);
    }
}

// 1. Create an audioPlayer instance.
let audioPlayer = media.createAudioPlayer();
SetCallBack(audioPlayer);                          // Set the event callbacks.
W
wusongqing 已提交
85
// 2. Set the URI of the audio file selected by the user.
W
wusongqing 已提交
86 87 88 89 90 91 92 93 94 95 96 97
let fdPath = 'fd://'
let path = 'data/accounts/account_0/appdata/ohos.xxx.xxx.xxx/01.mp3';
await fileIO.open(path).then(fdNumber) => {
   fdPath = fdPath + '' + fdNumber;
   console.info('open fd sucess fd is' + fdPath);
}, (err) => {
   console.info('open fd failed err is' + err);
}),catch((err) => {
   console.info('open fd failed err is' + err);
});

audioPlayer.src = fdPath;                         // Set the src attribute and trigger the 'dataLoad' event callback.
W
wusongqing 已提交
98 99
// 3. Play the audio file.
audioPlayer.play();                               // The play() API can be invoked only after the 'dataLoad' event callback is complete. The 'play' event callback is triggered.
W
wusongqing 已提交
100 101 102 103 104 105 106 107 108 109 110
// 4. Seek to the playback position.
audioPlayer.seek(30000);                          // Trigger the 'timeUpdate' event callback, and seek to 30000 ms for playback.
// 5. Set the volume.
audioPlayer.setVolume(0.5);                       // Trigger the 'volumeChange' event callback.
// 6. Pause the playback.
audioPlayer.pause();                              // Trigger the 'pause' event callback and pause the playback.
// 7. Obtain the track information.
audioPlayer.getTrackDescription((error, arrlist) => {  // Obtain the audio track information in callback mode.
    if (typeof (arrlist) != 'undefined') {
        for (let i = 0; i < arrlist.length; i++) {
            printfDescription(arrlist[i]);
M
mamingshuai 已提交
111
        }
W
wusongqing 已提交
112 113 114 115
    } else {
        console.log(`audio getTrackDescription fail, error:${error.message}`);
    }
});
W
wusongqing 已提交
116
// 8. Stop the playback.
W
wusongqing 已提交
117
audioPlayer.stop();                              // Trigger the 'stop' event callback.
W
wusongqing 已提交
118
// 9. Reset the player.
W
wusongqing 已提交
119 120
audioPlayer.reset();                             // Trigger the 'reset' event callback, and reconfigure the src attribute to switch to the next song.
// 10. Release the resource.
W
wusongqing 已提交
121
audioPlayer.release();                           // Release the AudioPlayer instance.
W
wusongqing 已提交
122 123 124 125 126 127
audioPlayer = undefined;
```

### Normal Playback Scenario

```js
W
wusongqing 已提交
128 129 130
import media from '@ohos.multimedia.media'
import fileIO from '@ohos.fileio'

W
wusongqing 已提交
131 132 133
function SetCallBack(audioPlayer) {
    audioPlayer.on('dataLoad', () => {              // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully.
        console.info('audio set source success');
W
wusongqing 已提交
134
        audioPlayer.play();                         // Call the play() API to start the playback and trigger the 'play' event callback.
W
wusongqing 已提交
135 136 137 138 139 140 141 142 143 144 145 146 147
    });
    audioPlayer.on('play', () => {                  // Set the 'play' event callback.
        console.info('audio play success');
    });
    audioPlayer.on('finish', () => {                // Set the 'finish' event callback, which is triggered when the playback is complete.
        console.info('audio play finish');
        audioPlayer.release();                      // Release the AudioPlayer instance.
		audioPlayer = undefined;
    });
}

let audioPlayer = media.createAudioPlayer();       // Create an AudioPlayer instance.
SetCallBack(audioPlayer);                          // Set the event callbacks.
W
wusongqing 已提交
148 149 150 151 152 153 154 155 156 157 158 159 160
/* Set the FD (local playback) of the audio file selected by the user. */
let fdPath = 'fd://'
let path = 'data/accounts/account_0/appdata/ohos.xxx.xxx.xxx/01.mp3';
await fileIO.open(path).then(fdNumber) => {
   fdPath = fdPath + '' + fdNumber;
   console.info('open fd sucess fd is' + fdPath);
}, (err) => {
   console.info('open fd failed err is' + err);
}),catch((err) => {
   console.info('open fd failed err is' + err);
});

audioPlayer.src = fdPath;                           // Set the src attribute and trigger the 'dataLoad' event callback.
W
wusongqing 已提交
161 162 163 164 165
```

### Switching to the Next Song

```js
W
wusongqing 已提交
166 167 168
import media from '@ohos.multimedia.media'
import fileIO from '@ohos.fileio'

W
wusongqing 已提交
169 170 171
function SetCallBack(audioPlayer) {
    audioPlayer.on('dataLoad', () => {              // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully.
        console.info('audio set source success');
W
wusongqing 已提交
172
        audioPlayer.play();                         // Call the play() API to start the playback and trigger the 'play' event callback.
W
wusongqing 已提交
173 174 175 176 177 178 179 180 181 182 183 184 185
    });
    audioPlayer.on('play', () => {                  // Set the 'play' event callback.
        console.info('audio play success');
    });
    audioPlayer.on('finish', () => {                // Set the 'finish' event callback, which is triggered when the playback is complete.
        console.info('audio play finish');
        audioPlayer.release();                      // Release the AudioPlayer instance.
		audioPlayer = undefined;
    });
}

let audioPlayer = media.createAudioPlayer();       // Create an AudioPlayer instance.
SetCallBack(audioPlayer);                          // Set the event callbacks.
W
wusongqing 已提交
186 187 188 189 190 191 192 193 194 195 196 197 198
/* Set the FD (local playback) of the audio file selected by the user. */
let fdPath = 'fd://'
let path = 'data/accounts/account_0/appdata/ohos.xxx.xxx.xxx/01.mp3';
await fileIO.open(path).then(fdNumber) => {
   fdPath = fdPath + '' + fdNumber;
   console.info('open fd sucess fd is' + fdPath);
}, (err) => {
   console.info('open fd failed err is' + err);
}),catch((err) => {
   console.info('open fd failed err is' + err);
});

audioPlayer.src = fdPath;                           // Set the src attribute and trigger the 'dataLoad' event callback.
W
wusongqing 已提交
199 200
/* Send the instruction to switch to the next song after a period of time. */
audioPlayer.reset();
W
wusongqing 已提交
201 202 203 204 205 206 207 208 209 210 211 212 213

/* Set the FD (local playback) of the audio file selected by the user. */
let fdNextPath = 'fd://'
let nextPath = 'data/accounts/account_0/appdata/ohos.xxx.xxx.xxx/01.mp3';
await fileIO.open(nextPath).then(fdNumber) => {
   fdNextPath = fdNextPath + '' + fdNumber;
   console.info('open fd sucess fd is' + fdNextPath);
}, (err) => {
   console.info('open fd failed err is' + err);
}),catch((err) => {
   console.info('open fd failed err is' + err);
});
audioPlayer.src = fdNextPath;
W
wusongqing 已提交
214 215 216 217 218
```

### Looping a Song

```js
W
wusongqing 已提交
219 220 221
import media from '@ohos.multimedia.media'
import fileIO from '@ohos.fileio'

W
wusongqing 已提交
222 223 224
function SetCallBack(audioPlayer) {
    audioPlayer.on('dataLoad', () => {              // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully.
        console.info('audio set source success');
W
wusongqing 已提交
225
        audioPlayer.play();                         // Call the play() API to start the playback and trigger the 'play' event callback.
W
wusongqing 已提交
226 227 228 229 230 231 232 233 234 235 236 237 238
    });
    audioPlayer.on('play', () => {                  // Set the 'play' event callback.
        console.info('audio play success');
    });
    audioPlayer.on('finish', () => {                // Set the 'finish' event callback, which is triggered when the playback is complete.
        console.info('audio play finish');
        audioPlayer.release();                      // Release the AudioPlayer instance.
		audioPlayer = undefined;
    });
}

let audioPlayer = media.createAudioPlayer();       // Create an AudioPlayer instance.
SetCallBack(audioPlayer);                          // Set the event callbacks.
W
wusongqing 已提交
239 240 241 242 243 244 245 246 247 248 249 250 251 252 253

/* Set the FD (local playback) of the audio file selected by the user. */
let fdPath = 'fd://'
let path = 'data/accounts/account_0/appdata/ohos.xxx.xxx.xxx/01.mp3';
await fileIO.open(path).then(fdNumber) => {
   fdPath = fdPath + '' + fdNumber;
   console.info('open fd sucess fd is' + fdPath);
}, (err) => {
   console.info('open fd failed err is' + err);
}),catch((err) => {
   console.info('open fd failed err is' + err);
});

audioPlayer.src = fdPath;                           // Set the src attribute and trigger the 'dataLoad' event callback.
audioPlayer.loop = true;                            // Set the loop playback attribute.
W
wusongqing 已提交
254
```