功能介紹:

播音音頻,提高音頻文件路徑,播放音頻。參考文檔使用AVPlayer開發音頻播放功能

知識點:

  1. 熟悉使用AVPlayer音視頻播放器。
  2. 讀取應用文件夾的本地音頻文件。
  3. 加載並播放音頻。

使用環境:

  • API 9
  • DevEco Studio 4.0 Release
  • Windows 11
  • Stage模型
  • ArkTS語言

所需權限:

  1. 只讀取應用文件夾內的音頻文件,不涉及額外目錄,不需要申請讀寫權限

註冊播放器回調函數代碼片段:

  setAVPlayerCallback() {
    this.avPlayer.on('error', (err) => {
      console.error(`播放器發生錯誤,錯誤碼:${err.code}, 錯誤信息:${err.message}`);
      // 調用reset重置資源,觸發idle狀態
      this.avPlayer.reset();
    })
    // 狀態機變化回調函數
    this.avPlayer.on('stateChange', async (state, reason) => {
      switch (state) {
        case 'initialized':
          console.info('資源初始化完成');
          // 資源初始化完成,開始準備文件
          this.avPlayer.prepare();
          break;
        case 'prepared':
          console.info('資源準備完成');
          // 資源準備完成,開始準備文件
          this.avPlayer.play();
          break;
        case 'completed':
          console.info('播放完成');
          this.avPlayer.stop();
          break;
      }
    })
  }

播放音頻函數片段:

  async onPageShow(){
    // 創建avPlayer實例對象
    this.avPlayer = await media.createAVPlayer();
    // 創建狀態機變化回調函數
    this.setAVPlayerCallback();
    console.info('播放器準備完成')
  }

  async avPlayerUrl() {
    let fdPath = 'fd://';
    // 獲取音頻路徑
    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(`音頻文件不存在:${path}`);
      promptAction.showToast({ message: "音頻文件不存在"})
      return
    }
    // 打開相應的資源文件地址獲取fd
    let file = await fs.open(path);
    fdPath = fdPath + '' + file.fd;
    // url賦值觸發initialized狀態機上報
    this.avPlayer.url = fdPath;
  }

完整代碼:

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(){
    // 創建avPlayer實例對象
    this.avPlayer = await media.createAVPlayer();
    // 創建狀態機變化回調函數
    this.setAVPlayerCallback();
    console.info('播放器準備完成')
  }

  build() {
    Row() {
      Column() {
        Button('播放音頻')
          .fontSize(16)
          .backgroundColor(Color.Blue)
          .onClick(()=>{
            this.avPlayerUrl()
          })
      }
      .width('100%')
    }
    .height('100%')
  }

  async avPlayerUrl() {
    let fdPath = 'fd://';
    // 獲取音頻路徑
    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(`音頻文件不存在:${path}`);
      promptAction.showToast({ message: "音頻文件不存在"})
      return
    }
    // 打開相應的資源文件地址獲取fd
    let file = await fs.open(path);
    fdPath = fdPath + '' + file.fd;
    // url賦值觸發initialized狀態機上報
    this.avPlayer.url = fdPath;
  }

  // 註冊avplayer回調函數
  setAVPlayerCallback() {
    this.avPlayer.on('error', (err) => {
      console.error(`播放器發生錯誤,錯誤碼:${err.code}, 錯誤信息:${err.message}`);
      // 調用reset重置資源,觸發idle狀態
      this.avPlayer.reset();
    })
    // 狀態機變化回調函數
    this.avPlayer.on('stateChange', async (state, reason) => {
      switch (state) {
        case 'initialized':
          console.info('資源初始化完成');
          // 資源初始化完成,開始準備文件
          this.avPlayer.prepare();
          break;
        case 'prepared':
          console.info('資源準備完成');
          // 資源準備完成,開始準備文件
          this.avPlayer.play();
          break;
        case 'completed':
          console.info('播放完成');
          this.avPlayer.stop();
          break;
      }
    })
  }
}
小夜