Function Introduction:¶
Play audio by specifying the audio file path and playing the audio. Refer to the documentation Using AVPlayer to Develop Audio Playback Function.
Key Knowledge Points:¶
- Familiarity with using the AVPlayer audio/video player.
- Reading local audio files from the application’s folder.
- Loading and playing audio.
Usage Environment:¶
- API 9
- DevEco Studio 4.0 Release
- Windows 11
- Stage Model
- ArkTS Language
Required Permissions:¶
- Only read audio files within the application’s folder. No additional directories are involved, so no read/write permissions are required.
Code Snippet for Registering Player Callback Functions:¶
setAVPlayerCallback() {
this.avPlayer.on('error', (err) => {
console.error(`Player error occurred, error code: ${err.code}, error message: ${err.message}`);
// Call reset to release resources and trigger the idle state
this.avPlayer.reset();
})
// State machine change callback function
this.avPlayer.on('stateChange', async (state, reason) => {
switch (state) {
case 'initialized':
console.info('Resource initialization completed');
// Start preparing the file after resource initialization is complete
this.avPlayer.prepare();
break;
case 'prepared':
console.info('Resource preparation completed');
// Start playing the file after resource preparation is complete
this.avPlayer.play();
break;
case 'completed':
console.info('Playback completed');
this.avPlayer.stop();
break;
}
})
}
Code Snippet for Playing Audio:¶
async onPageShow(){
// Create an AVPlayer instance
this.avPlayer = await media.createAVPlayer();
// Register state machine change callback
this.setAVPlayerCallback();
console.info('Player prepared successfully')
}
async avPlayerUrl() {
let fdPath = 'fd://';
// Get the audio file path
let context = getContext(this) as common.UIAbilityContext;
let pathDir = context.filesDir;
let path = pathDir + '/test.wav';
let res = fs.accessSync(path);
if (!res) {
console.error(`Audio file not found: ${path}`);
promptAction.showToast({ message: "Audio file not found"})
return
}
// Open the resource file to get the file descriptor (fd)
let file = await fs.open(path);
fdPath = fdPath + '' + file.fd;
// Assign the URL to trigger the 'initialized' state machine event
this.avPlayer.url = fdPath;
}
Complete Code:¶
import media from '@ohos.multimedia.media';
import fs from '@ohos.file.fs';
import common from '@ohos.app.ability.common';
import promptAction from '@ohos.promptAction';
@Entry
@Component
struct PlayAudio {
private avPlayer;
async onPageShow(){
// Create an AVPlayer instance
this.avPlayer = await media.createAVPlayer();
// Register state machine change callback
this.setAVPlayerCallback();
console.info('Player prepared successfully')
}
build() {
Row() {
Column() {
Button('Play Audio')
.fontSize(16)
.backgroundColor(Color.Blue)
.onClick(()=>{
this.avPlayerUrl()
})
}
.width('100%')
}
.height('100%')
}
async avPlayerUrl() {
let fdPath = 'fd://';
// Get the audio file path
let context = getContext(this) as common.UIAbilityContext;
let pathDir = context.filesDir;
let path = pathDir + '/test.wav';
let res = fs.accessSync(path);
if (!res) {
console.error(`Audio file not found: ${path}`);
promptAction.showToast({ message: "Audio file not found"})
return
}
// Open the resource file to get the file descriptor (fd)
let file = await fs.open(path);
fdPath = fdPath + '' + file.fd;
// Assign the URL to trigger the 'initialized' state machine event
this.avPlayer.url = fdPath;
}
// Register AVPlayer callback functions
setAVPlayerCallback() {
this.avPlayer.on('error', (err) => {
console.error(`Player error occurred, error code: ${err.code}, error message: ${err.message}`);
// Call reset to release resources and trigger the idle state
this.avPlayer.reset();
})
// State machine change callback function
this.avPlayer.on('stateChange', async (state, reason) => {
switch (state) {
case 'initialized':
console.info('Resource initialization completed');
// Start preparing the file after resource initialization is complete
this.avPlayer.prepare();
break;
case 'prepared':
console.info('Resource preparation completed');
// Start playing the file after resource preparation is complete
this.avPlayer.play();
break;
case 'completed':
console.info('Playback completed');
this.avPlayer.stop();
break;
}
})
}
}