一个笔记:笔者整理的 MP3 文件信息获取的API ,Unity 适用。
完整代码:
using System;
using System.IO;
using UnityEngine;
namespace mp3infos
{
public struct MP3Info
{
public string Title;
public string Singer;
public string Album;
public string Year;
public string Comment;
public override string ToString()
{
return "MP3附加信息:" + Environment.NewLine +
"-----------------------------" + Environment.NewLine +
"标 题: " + Title + Environment.NewLine +
"歌 手: " + Singer + Environment.NewLine +
"唱片集: " + Album + Environment.NewLine +
"出版期: " + Year + Environment.NewLine +
"备 注: " + Comment;
}
}
public class MP3Helper
{
public static MP3Info ReadMP3Info(string path)
{
try
{
using (FileStream fs = new FileStream(path, FileMode.Open))
{
return StreamHandler(fs);
}
}
catch (Exception e)
{
Debug.Log(e.Message);
}
return default(MP3Info);
}
public static MP3Info ReadMP3Info(Stream stream)
{
return StreamHandler(stream);
}
private static MP3Info StreamHandler(Stream stream)
{
byte[] b = new byte[128];
MP3Info mp3struct = new MP3Info();
stream.Seek(-128, SeekOrigin.End);
stream.Read(b, 0, 128);
string MP3Flag = System.Text.Encoding.Default.GetString(b, 0, 3);
if (MP3Flag == "TAG")
{
mp3struct.Title = System.Text.Encoding.Default.GetString(b, 3, 30);
mp3struct.Singer = System.Text.Encoding.Default.GetString(b, 33, 30);
mp3struct.Album = System.Text.Encoding.Default.GetString(b, 63, 30);
mp3struct.Year = System.Text.Encoding.Default.GetString(b, 93, 4);
mp3struct.Comment = System.Text.Encoding.Default.GetString(b, 97, 30);
}
return mp3struct;
}
}
}
使用方法:
- 使用 mp3 路径(这种方式要注意访问MP3文件的先后顺序(亦即是先获取文件信息再播放它),避免占用问题)
string path = "d://xxx/xx/my.mp3"
MP3Info info = MP3Helper.ReadMP3Info(path);
if (!string.IsNullOrEmpty(info.Title))
{
Debug.Log(info.ToString());
}
- 使用 mp3 数据流
//此处数据流多为为网络加载的情景
MP3Info info = MP3Helper.ReadMP3Info(stream);
if (!string.IsNullOrEmpty(info.Title))
{
Debug.Log(info.ToString());
}
Debug效果:
Tips : 笔者在测试时发现如果出版日期留空就只能得到歌曲名称。所以还有优化空间,有兴趣的可以提交修改版,超级欢迎。
网友评论