使用FFMpeg 獲取MP3檔案中的資訊和圖片
阿新 • • 發佈:2018-12-13
我們在播放音訊檔案時,如MP3格式的音訊檔案,一些播放器會顯示音樂名稱、專輯名稱、歌手、音樂影象等資訊,如下圖片所示: 下面介紹使用FFMpeg來獲取這些資訊。
- 使用函式avformat_open_input開啟檔案,結封裝。
- 使用函式avformat_find_stream_info查詢並新增流資訊到Format上下文中。
- 使用函式av_dict_get獲取檔案中的字典資訊。
下面是關鍵部分程式碼:
1.獲取音樂相關資訊
獲取檔案中的資訊:
// 開啟檔案
int result = avformat_open_input(&m_AVFormatContext, fileName.toLocal8Bit ().data(), nullptr, nullptr);
if (result != 0 || m_AVFormatContext == nullptr)
return false;
// 查詢流資訊,把它存入AVFormatContext中
if (avformat_find_stream_info(m_AVFormatContext, nullptr) < 0)
return false;
int streamsCount = m_AVFormatContext->nb_streams;
// 讀取詳細資訊
AVDictionaryEntry *tag = nullptr;
while (tag = av_dict_get(m_AVFormatContext->metadata, "", tag, AV_DICT_IGNORE_SUFFIX))
{
QString keyString = tag->key;
QString valueString = QString::fromUtf8(tag->value);
m_InfoMap.insert(keyString, valueString);
}
這裡將資訊放到了一個QMap中儲存。 下面是我本地的音訊檔案中的得到的字典資訊:
title表示歌曲名,album表示專輯名稱,artist表示藝術家(歌手)
2.獲取圖片
獲取圖片程式碼關鍵部分如下:
int streamsCount = m_AVFormatContext->nb_streams;
for (int i=0; i<streamsCount; ++i)
{
if (m_AVFormatContext->streams[i]->disposition & AV_DISPOSITION_ATTACHED_PIC)
{
AVPacket pkt = m_AVFormatContext->streams[i]->attached_pic;
m_InfoImage = QImage::fromData((uchar*)pkt.data, pkt.size);
}
}
這裡將圖片資訊存入到QImage型別的名為m_InfoImage的成員變數中。