music-database.ts•3.13 kB
export interface Song {
id: string;
title: string;
artist: string;
album: string;
year: number;
duration: string;
genre: string;
playCount: number;
rating: number;
}
export class MusicDatabase {
private songs: Song[] = [
{
id: '1',
title: '成都',
artist: '赵雷',
album: '无法长大',
year: 2016,
duration: '5:28',
genre: '民谣',
playCount: 1500000,
rating: 5,
},
{
id: '2',
title: '南方姑娘',
artist: '赵雷',
album: '赵小雷',
year: 2012,
duration: '4:42',
genre: '民谣',
playCount: 1200000,
rating: 5,
},
{
id: '3',
title: '理想',
artist: '赵雷',
album: '无法长大',
year: 2016,
duration: '5:13',
genre: '民谣',
playCount: 980000,
rating: 5,
},
{
id: '4',
title: '画',
artist: '赵雷',
album: '吉姆餐厅',
year: 2013,
duration: '4:08',
genre: '民谣',
playCount: 850000,
rating: 5,
},
{
id: '5',
title: '我们的时光',
artist: '赵雷',
album: '无法长大',
year: 2016,
duration: '4:36',
genre: '民谣',
playCount: 920000,
rating: 5,
},
];
async search(query: string, type: string = 'all', limit: number = 10): Promise<Song[]> {
const lowerQuery = query.toLowerCase();
let filtered = this.songs.filter(song => {
switch (type) {
case 'song':
return song.title.toLowerCase().includes(lowerQuery);
case 'artist':
return song.artist.toLowerCase().includes(lowerQuery);
case 'album':
return song.album.toLowerCase().includes(lowerQuery);
case 'all':
default:
return (
song.title.toLowerCase().includes(lowerQuery) ||
song.artist.toLowerCase().includes(lowerQuery) ||
song.album.toLowerCase().includes(lowerQuery)
);
}
});
return filtered.slice(0, limit);
}
async getSongById(id: string): Promise<Song | undefined> {
return this.songs.find(song => song.id === id);
}
async getRecommendations(genre?: string, mood?: string, limit: number = 10): Promise<Song[]> {
let filtered = [...this.songs];
if (genre) {
filtered = filtered.filter(song =>
song.genre.toLowerCase().includes(genre.toLowerCase())
);
}
// 根据心情推荐(简单的逻辑示例)
if (mood) {
const moodLower = mood.toLowerCase();
if (moodLower.includes('快乐') || moodLower.includes('开心')) {
filtered = filtered.filter(song => song.genre === 'Pop');
} else if (moodLower.includes('安静') || moodLower.includes('放松')) {
filtered = filtered.filter(song => song.rating >= 4);
}
}
// 按评分和播放次数排序
filtered.sort((a, b) => (b.rating * b.playCount) - (a.rating * a.playCount));
return filtered.slice(0, limit);
}
async getAllSongs(): Promise<Song[]> {
return [...this.songs];
}
}