0
点赞
收藏
分享

微信扫一扫

Vue中使用benz-amr-recorder插件实现播放amr音频文件以及在线url跨域问题解决


场景

需要做一个Android端和Web端的聊天室,Android端的录音音频文件为.amr格式,除了

通过后台server端转码之后,是否可以通过插件在前端直接播放amr的音频文件。

benz-amr-recorder

​​AMR 录音机 | benz-amr-recorder​​

纯前端解码、播放、录音、编码 AMR 音频,无须服务器支持,基于 amr.js 和 RecorderJs。

在线演示demo

​​AMR decode/encode tests​​

注:

实现

1、安装插件

npm install benz-amr-recorder

2、播放amr

var amr = new BenzAMRRecorder();
amr.initWithUrl('path/to/voice.amr').then(function() {
amr.play();
});
amr.onEnded(function() {
alert('播放完毕');
})

3、在Vue中使用

<el-button type="button" @click="playAmrData">播放amr录音数据</el-button>

data() {
return {
amr: null,
};
},

点击调用的方法

//播放amr音频文件
playAmrData(){
this.amr = new BenzAMRRecorder();
this.amr.initWithUrl("http://ip:20201/profile/upload/2022/09/22/0dfd2965-0427-4cc8-9702-d4f7fdf9c047.amr")
.then(()=>{
this.amr.play();
})
.catch((e)=>{
this.$message.error("播放失败");
})
},

注意:

上面的url是amr文件的网络url,这里是本地静态资源映射的地址。

4、跨域问题

但是在播放时提示跨域

看一下官方对于跨域问题的说明

 

 

所以需要后台服务解决跨域问题。这里后台静态资源映射使用的SpringBoot

SpringBoot中重写addCorsMapping解决跨域以及提示list them explicitly or consider using “allowedOriginPatterns“ in

​​SpringBoot中重写addCorsMapping解决跨域以及提示list them explicitly or consider using “allowedOriginPatterns“ in_霸道流氓气质的博客-CSDN博客​​

添加配置类代码

package com.chrisf.config;

import com.chrisf.constant.Constants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;


@Configuration
@SuppressWarnings("SpringJavaAutowiredFieldsWarningInspection")
public class ResourcesConfig implements WebMvcConfigurer {

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
/** 本地文件上传路径 */
registry.addResourceHandler(Constants.RESOURCE_PREFIX + "/**").addResourceLocations("file:" + RuoYiConfig.getProfile() + "/");
}

@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**") // 拦截所有的请求
//.allowedOrigins("*") // 可跨域的域名,可以为 *
.allowedOriginPatterns("*")
.allowCredentials(true)
.allowedMethods("*") // 允许跨域的方法,可以单独配置
.allowedHeaders("*"); // 允许跨域的请求头,可以单独配置
}
}

举报

相关推荐

0 条评论