audio-playback.md 8.9 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 9 10 11 12 13 14 15 16 17 18

![en-us_image_20220117](figures/en-us_image_20220117.jpg)

## 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

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 resources, and releasing resources.

W
wusongqing 已提交
19
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 已提交
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

```js
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 已提交
46 47
            return;
        }
W
wusongqing 已提交
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
        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.
// 2. Set the URI of the audio file.
audioPlayer.src = 'file:///data/data/ohos.xxx.xxx/files/test.mp3';  // Set the src attribute and trigger the 'dataLoad' event callback.
// 3. Play the audio.
audioPlayer.play();                               // The play() method can be invoked only after the 'dataLoad' event callback is complete. The 'play' event callback is triggered.
// 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 已提交
91
        }
W
wusongqing 已提交
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 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179
    } else {
        console.log(`audio getTrackDescription fail, error:${error.message}`);
    }
});
// 8. Stop playback.
audioPlayer.stop();                              // Trigger the 'stop' event callback.
// 9. Reset the playback resources.
audioPlayer.reset();                             // Trigger the 'reset' event callback, and reconfigure the src attribute to switch to the next song.
// 10. Release the resource.
audioPlayer.release();                           // Release the AudioPlayer resource.
audioPlayer = undefined;
```

### Normal Playback Scenario

```js
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');
        audioPlayer.play();                         // Call the play() method to start the playback and trigger the 'play' event callback.
    });
    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.
/* Set the URI of the audio file selected by the user. */
audioPlayer.src = 'file:///data/data/ohos.xxx.xxx/files/test.mp3';  // Set the src attribute and trigger the 'dataLoad' event callback.
```

### Switching to the Next Song

```js
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');
        audioPlayer.play();                         // Call the play() method to start the playback and trigger the 'play' event callback.
    });
    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.
/* Set the URI of the audio file selected by the user. */
audioPlayer.src = 'file:///data/data/ohos.xxx.xxx/files/test.mp3';  // Set the src attribute and trigger the 'dataLoad' event callback.
/* Send the instruction to switch to the next song after a period of time. */
audioPlayer.reset();
audioPlayer.src = 'file:///data/data/ohos.xxx.xxx/files/next.mp3';
```

### Looping a Song

```js
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');
        audioPlayer.play();                         // Call the play() method to start the playback and trigger the 'play' event callback.
    });
    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.
/* Set the URI of the audio file selected by the user. */
audioPlayer.src = 'file:///data/data/ohos.xxx.xxx/files/test.mp3';  // Set the src attribute and trigger the 'dataLoad' event callback.
audioPlayer.loop = true;                           // Set the loop playback attribute.
```