amr文件播放前端实现

最近工作的时候发现了这样的一个问题,amr格式的文件audio标签不能解码播放。

查了下mdn相关资料,发现确实是不支持amr后缀的文件

一般情况下是不会有这样的需求的,问题是当后端不愿意去做这个事的时候,就得想办法了。

上网查资料发现了这么一个解码amr的库

那我们要做的就是在此基础上提供的api来封装一个audio播放器,忽略UI因素,要满足如下几个场景

  1. 支持播放暂停
  2. 支持进度条显示
  3. amr和普通文件可以使用同一套api

于是基于原生audio的一些特性和解码库,封装了一个工具库

这里放一个基于vue二次封装使用的例子,有同样需求的朋友可以使用,欢迎提建议和star

<template>
  <div class="player" v-loading="loading">
    <i
      :class="state==='pause'?'el-icon-video-play btn':'el-icon-video-pause btn'"
      @click="playOrPause"
    ></i>
    <el-progress :percentage="percentage" :show-text="false"></el-progress>
  </div>
</template>

<script >
import { AudioPlayer } from "audio-amr-player";

export default {
  data() {
    return {
      percentage: 0,
      state: "pause",
      loading: true
    };
  },
  props: {
    url: {
      type: String
    },
    file: {
      type: File,
      validator(val) {
        return val instanceof File;
      }
    }
  },

  watch: {
    url() {
      this.init();
    },
    file() {
      this.init();
    }
  },

  mounted() {
    this.init();
  },

  methods: {
    playOrPause() {
      if (this.state === "pause") {
        this.state = "play";
        this.player.play();
      } else {
        this.state = "pause";
        this.player.pause();
      }
    },
    init() {
      let _this = this;
      this.player = new AudioPlayer({
        url: this.url,
        file: this.file,
        afterInit() {
          _this.loading = false;
        }
      });
      this.player.onTimeUpdate(time => {
        let rate =
          time > this.player.duration ? 1 : time / this.player.duration;
        this.percentage = rate * 100;
      });
      this.player.onEnd(() => {
        this.state = "pause";
      });
    }
  },
  beforeDestroy() {
    this.player.destroy();
  }
};
</script>
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容