企业微信 语音消息 -优化版
想查看web端react-amr的API可以去看此链接 添加链接描述
简说一下:
一般我们使用移动端微信发的语音是amr文件不是MP3文件;
而且web端不支持,所以我们要找对应的amr的三方资源去协助我们开发
这边是通过文件流来获取,如果你想做调试的话,网上amr的文件资源不好找,你可以使用转换器,将你的MP3文件转换成amr文件到本地就可以使用啦!!!
/**
* @文件描述 会话管理界面右侧---协助左侧渲染 -语音消息
* @创建人和时间 - 2021-04-28
* @更新人和时间 - 2021-05-11
* @param {Function} amr - 初始化amr
* @param {boolean} isToggleOn - 控制播放暂停图标
*/
import React, { PureComponent } from 'react';
import BenzAMRRecorder from 'benz-amr-recorder';
import { Col, Row, Card } from 'antd';
import { PlayCircleOutlined, PauseCircleOutlined } from '@ant-design/icons';
// import amrCeshi from "../../../../assets/audio/amrCeshi.amr"; // 测试使用
import { wechatV1 as v1 } from 'services/config';
import { getAccessToken } from 'utils/token';
export default class Voices extends PureComponent {
constructor(props) {
super(props);
this.state = {
amr: new BenzAMRRecorder(),
isToggleOn: true, // 控制播放暂停图标
}
this.change = this.change.bind(this);
}
// 点击开始播放
change = () => {
const { amr } = this.state;
if (amr.isPaused()) {
amr.play();
} else {
const { item } = this.props;
const that = this;
const token = getAccessToken();
fetch(`${v1}/wechat/content/${item.id}/media`, {
headers: { authorization: `Bearer ${token}` },
responseType: 'blob',
})
.then(res => {
that.setState({ data: res })
return res.blob()
}).then(res => {
const reader = new FileReader();
reader.readAsDataURL(res);
reader.onload = (e) => {
that.setState({ img: e.target.result })
// amr请求
amr.initWithUrl(e.target.result).then(() => {
if (amr.isPlaying()) {
amr.onPlay();
} else {
amr.play();
}
});
// 播放完成自动回到开始播放按钮
amr.onEnded(() => {
this.setState({
amr: new BenzAMRRecorder(),
isToggleOn: true,
})
})
}
})
}
this.setState(prevState => ({
isToggleOn: !prevState.isToggleOn,
}))
}
// 点击停止播放
consol = () => {
const { amr } = this.state;
this.setState(prevState => ({
isToggleOn: !prevState.isToggleOn,
}))
amr.onPause(() => {
console.log(1)
})
amr.pause();
}
render() {
const { isToggleOn } = this.state;
const { item } = this.props;
return (
<Card size="small" hoverable style={{width:226}}>
<div style={{ padding: '0px 8px', width: 200, height: 28, backgroundColor: '#eee', borderRadius: "12px" }}>
{
isToggleOn
? (
<Row onClick={() => this.change()} style={{ cursor: "pointer" }}>
<PlayCircleOutlined style={{ fontSize: 19, paddingTop: 5, paddingRight: 2, paddingLeft: 2 }} />
<Col span={10} style={{ marginTop: 3, paddingLeft: 6 }}>开始播放</Col>
<Col style={{ fontSize: 12, marginLeft: 8, marginTop: 5 }}>总时长:{item.v_play_length} S</Col>
</Row>
)
: (
<Row onClick={() => this.consol()}>
<PauseCircleOutlined style={{ fontSize: 19, paddingTop: 5, paddingRight: 2, paddingLeft: 2 }} />
<Col span={10} style={{ marginTop: 3, paddingLeft: 6 }}>停止播放</Col>
<Col style={{ fontSize: 12, marginLeft: 8, marginTop: 5 }}>总时长:{item.v_play_length} S</Col>
</Row>
)
}
</div>
</Card>
)
}
}
页面展示
此页面样式自己写的,仅做参考
点击按钮就可以播放,播放完会自动暂停,点击暂停按钮也会自动停止;再次点击的话,会重新播放