electron + ts + vue读取mp3 歌名、歌手
时间: 2023-06-24 08:05:58 浏览: 68
要读取 MP3 文件的元数据(包括歌名和歌手),您可以使用一个名为 `music-metadata` 的 NPM 包。这个包可以解析多种音频文件的元数据,包括 MP3。
下面是一个使用 Electron、TypeScript 和 Vue 的例子:
首先,安装 `music-metadata` 包:
```
npm install --save music-metadata
```
然后,您可以创建一个名为 `MetadataReader.ts` 的 TypeScript 类来读取 MP3 文件的元数据:
```typescript
import * as mm from 'music-metadata';
export class MetadataReader {
public static async readMetadata(filePath: string): Promise<{ artist?: string, title?: string }> {
const metadata = await mm.parseFile(filePath);
return {
artist: metadata.common.artist,
title: metadata.common.title
};
}
}
```
上面的代码将返回一个包含 `artist` 和 `title` 键的对象,这些键分别对应 MP3 文件的艺术家和歌曲名称。如果元数据中不存在这些值,则相应的键将为 `undefined`。
最后,您可以在 Vue 组件中使用此类来读取 MP3 文件的元数据。例如,在一个名为 `MusicPlayer.vue` 的组件中:
```vue
<template>
<div>
<h1>{{ metadata.title }}</h1>
<h2>{{ metadata.artist }}</h2>
<audio :src="filePath" controls></audio>
</div>
</template>
<script lang="ts">
import { Component, Vue } from 'vue-property-decorator';
import { MetadataReader } from './MetadataReader';
@Component
export default class MusicPlayer extends Vue {
public filePath = 'path/to/your/mp3/file.mp3';
public metadata = {};
public async mounted(): Promise<void> {
this.metadata = await MetadataReader.readMetadata(this.filePath);
}
}
</script>
```
上面的代码将在组件挂载时读取元数据,并将其存储在 `metadata` 对象中。您可以在模板中使用此对象来显示歌曲名称和艺术家,并使用 `audio` 元素播放 MP3 文件。
请注意,上面的代码仅供参考,您需要根据您的具体需求进行修改。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)