音乐播放(AVPlayer)鸿蒙Next

大概就是像上面这样

首先 ,这里使用的是本地音频,所有,要把音频放到rawfile目录下,

然后我们先把布局搭起来,并且创建想要的列表,创建播放的索引,对应列表中想要的MusicClass对象


// 创建一个音频,?就说明了他可能没有
avPlayer?: media.AVPlayer;
  // 点击按钮的播放和暂停
  @State isPlay:boolean=false;
  // 创建一个音乐数组
  @State musicList:MusicClass[] = [
    new MusicClass('简单爱','周杰伦','easy_love.mp3',$r('app.media.zjl')),
    new MusicClass('青花','周传雄','qinhua.mp3',$r('app.media.zcx')),
    new MusicClass('年少有为','李荣浩','nianshaoyouwei.mp3',$r('app.media.lrh'))
  ]
  //当前播放的⾳乐
  @State currentMusic:MusicClass = this.musicList[0]
  //当前播放⾳乐的索引
  @State currentIndex:number = 1

build() {
    Column(){
      //1、歌曲信息展示区域---------------------------------------------------------------------
      Column({space:20}){
        Image(this.musicList[this.currentIndex].img)
          .width(200)
          .height(200)
          .borderRadius(100)
        Text(this.musicList[this.currentIndex].title)
          .fontColor('#222628')
          .fontSize(24)
      }
      .width('100%')
      .alignItems(HorizontalAlign.Center)
      Text(this.musicList[this.currentIndex].singer)
        .fontColor('#76777A')
        .fontSize(14)
        .margin({top:10})

      Row(){
        //上⼀⾸按钮
        Image($r('app.media.control_last'))
          .width(32)
          .height(32)
          .objectFit(ImageFit.Auto)
          .onClick(()=>{
            // 点击事件
          })
        //播放按钮,这里对应的是播放和暂停的icon
        Image( this.isPlay ? $r('app.media.control_pause') : $r('app.media.control_play'))
          .width(64)
          .height(64)
          .onClick(()=>{
            // 点击事件
          })
        // 下一首按钮
        Image($r('app.media.control_next'))
          .width(32)
          .height(32)
          .objectFit(ImageFit.Auto)
          .onClick(()=>{
          // 点击事件
          })
      }
      .margin({top:30})
      .width('70%')
      .justifyContent(FlexAlign.SpaceBetween)
    }
    .width('100%')
    .height('100%')
    .justifyContent(FlexAlign.Center)
  }

这里的情况下有个类

然后,我们需要创建了AVplayer对象实例,监听avPlayer的状态改变

这里建议用Switch去使用,不要用if,因为他的点比较多

接下来设置播放源,

后面修改他对应的状态就可以了

export class MusicClass {
  title: string
  singer: string
  url: string
  img:ResourceStr

  constructor(title: string, singer: string, url: string,img:ResourceStr) {
    this.title = title
    this.singer = singer
    this.url = url
    this.img=img
  }
}

以下是全部的代码,需要导入上面的类

import media from '@ohos.multimedia.media';
import { MusicClass } from './MyClass';


@Entry
@Component
struct MugicPage {
  avPlayer?: media.AVPlayer;
  // 点击按钮的播放和暂停
  @State isPlay:boolean=false;
  // 创建一个音乐数组
  @State musicList:MusicClass[] = [
    new MusicClass('简单爱','周杰伦','easy_love.mp3',$r('app.media.zjl')),
    new MusicClass('青花','周传雄','qinhua.mp3',$r('app.media.zcx')),
    new MusicClass('年少有为','李荣浩','nianshaoyouwei.mp3',$r('app.media.lrh'))
  ]
  //当前播放的⾳乐
  @State currentMusic:MusicClass = this.musicList[0]
  //当前播放⾳乐的索引
  @State currentIndex:number = 1



  // 设置最开始的进度
  aboutToAppear() {
    this.playMp3(this.musicList[this.currentIndex].url)
  }
  onPageShow() {
    this.playMp3(this.musicList[this.currentIndex].url)
  }



    async playMp3(url: string) {
      //  1. 创建了AVplayer对象实例
      const avPlayer = await media.createAVPlayer()
      this.avPlayer = avPlayer
      // 2. 监听avPlayer的状态改变
      //avPlayer的状态机
      avPlayer.on("stateChange", async (state) => {
        if (state === "initialized") {
          //   表示avPlayer已经设置了播放源
          avPlayer.prepare()
        }
        if (state === "prepared") {
          //  表示avPlayer已经进入了准备播放状态,此时就可以通知播放了
          // 设置avPlayer循环播放音频
          avPlayer.loop = true
          // avPlayer.play(),不要让它进来就播放,要自己点击的时候播放
          // promptAction.showToast({ message: '正在播放' })
        }
      })
      //   3. 设置播放源
      const fd = getContext().resourceManager.getRawFdSync(url)
      this.avPlayer.fdSrc = { fd: fd.fd, offset: fd.offset, length: fd.length }

      // 设置错误提示
      this.avPlayer.on("error", (error) => {
        console.error("播放出错:", error);
      });
    }


  build() {
    Column(){
      //1、歌曲信息展示区域---------------------------------------------------------------------
      Column({space:20}){
        Image(this.musicList[this.currentIndex].img)
          .width(200)
          .height(200)
          .borderRadius(100)
        Text(this.musicList[this.currentIndex].title)
          .fontColor('#222628')
          .fontSize(24)
      }
      .width('100%')
      .alignItems(HorizontalAlign.Center)
      Text(this.musicList[this.currentIndex].singer)
        .fontColor('#76777A')
        .fontSize(14)
        .margin({top:10})

      Row(){
        //上⼀⾸按钮
        Image($r('app.media.control_last'))
          .width(32)
          .height(32)
          .objectFit(ImageFit.Auto)
          .onClick(()=>{
            // 判断索引值是否小于数组的长度
            if (this.currentIndex===1) {
              // 点击的时候就让他+1,并且重启
              this.currentIndex-=1
              this.avPlayer?.reset()
              this.playMp3(this.musicList[this.currentIndex].url)
              this.isPlay=false
            }else {
              this.currentIndex=this.musicList.length-1
              this.avPlayer?.reset()
              this.playMp3(this.musicList[this.currentIndex].url)
              this.isPlay=false
            }
          })
        //播放按钮
        Image( this.isPlay ? $r('app.media.control_pause') : $r('app.media.control_play'))
          .width(64)
          .height(64)
          .onClick(()=>{
            //切换当前状态
            this.isPlay = !this.isPlay
            if(this.isPlay)
            {
              //播放
              if (this.avPlayer != undefined) {
                if(this.avPlayer.state != 'playing'){
                  this.avPlayer.play()
                }else {
                  this.avPlayer.pause()
                }
              }
            }
            else {
              //暂定
              if (this.avPlayer != undefined) {
                this.avPlayer.pause()
              }
            }
          })
        // 下一首按钮
        Image($r('app.media.control_next'))
          .width(32)
          .height(32)
          .objectFit(ImageFit.Auto)
          .onClick(()=>{
            // 判断索引值是否小于数组的长度
            if (this.currentIndex<this.musicList.length-1) {
              // 点击的时候就让他+1,并且重启
              this.currentIndex+=1
              this.avPlayer?.reset()
              this.playMp3(this.musicList[this.currentIndex].url)
              this.isPlay=false
            }else {
              this.currentIndex=0
              this.avPlayer?.reset()
              this.playMp3(this.musicList[this.currentIndex].url)
              this.isPlay=false
            }

          })
      }
      .margin({top:30})
      .width('70%')
      .justifyContent(FlexAlign.SpaceBetween)
    }
    .width('100%')
    .height('100%')
    .justifyContent(FlexAlign.Center)
  }

}

以上只是音乐播放器的一部分,具体的可以自己去扩展。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值