uni-app如何获取用户的本机录音文件,并展示在页面中?
时间: 2024-03-09 21:48:35 浏览: 17
要获取用户本机的录音文件并展示在页面中,您可以使用uni-app提供的文件API进行文件读取和展示。以下是一个简单的示例代码:
```javascript
<template>
<div class="container">
<div class="header">录音列表</div>
<div class="list">
<div v-for="(item, index) in fileList" :key="index" class="item" @click="playAudio(item.path)">
<div class="name">{{ item.name }}</div>
<div class="duration">{{ item.duration }}s</div>
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
fileList: [] // 录音文件列表
};
},
mounted() {
// 获取录音文件列表
this.getRecordList();
},
methods: {
// 获取录音文件列表
getRecordList() {
uni.getSavedFileList({
success: (res) => {
console.log('获取录音文件列表成功', res);
this.fileList = res.fileList.filter((item) => {
return item.filePath.indexOf('.silk') > -1; // 过滤出silk格式的录音文件
}).map((item) => {
return {
name: item.filePath.substring(item.filePath.lastIndexOf('/') + 1, item.filePath.lastIndexOf('.silk')),
path: item.filePath,
duration: Math.ceil(item.size / 1024 / 8) // 粗略计算录音时长
};
});
},
fail: (err) => {
console.error('获取录音文件列表失败', err);
}
});
},
// 播放录音
playAudio(path) {
uni.playVoice({
filePath: path,
success: () => {
console.log('播放录音成功');
},
fail: (err) => {
console.error('播放录音失败', err);
}
});
}
}
};
</script>
<style>
.container {
display: flex;
flex-direction: column;
height: 100vh;
}
.header {
height: 44px;
line-height: 44px;
text-align: center;
font-size: 16px;
color: #333;
}
.list {
flex: 1;
overflow: auto;
}
.item {
display: flex;
align-items: center;
justify-content: space-between;
height: 44px;
padding: 0 16px;
background-color: #fff;
border-bottom: 1px solid #e5e5e5;
font-size: 14px;
color: #666;
}
.name {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.duration {
margin-left: 12px;
}
</style>
```
以上代码会获取用户设备本地保存的录音文件列表,并展示在页面中,用户可以点击录音文件进行播放。需要注意的是,用户在录音时需要授权uni-app使用麦克风,并且需要过滤出指定格式的录音文件进行展示。