手机多媒体开发的时候经常需要后台扫描音乐文件,本篇使用qt一些库实现简单的后台扫描的类,继承了Qthread
playlist.h

#ifndef PLAYLIST_H
#define PLAYLIST_H

#include <QDir>
#include <QFileInfo>
#include <QFileSystemModel>
#include <QObject>
#include <QDirIterator>
#include <QtDebug>
#include <QString>
#include <QList>
#include <QFileInfo>
#include <QDebug>
#include <QJsonArray>
#include <QJsonObject>
#include <QThread>
#include <QMutex>
#include <QtConcurrent>
#include <QThreadPool>

class PlayList : public QThread
{
    Q_OBJECT
public:
    explicit PlayList(QObject *parent = 0);
    ~PlayList();

    Q_PROPERTY(QJsonArray playlist READ playlist NOTIFY playlistChanged)
    QJsonArray playlist();

    Q_INVOKABLE void findMusic();

    Q_INVOKABLE int getItemsLength(){
        return musicPath.count();
    }
    Q_INVOKABLE QString getMusicName(int id){
        return musicPath.at(id).fileName();
    }
    Q_INVOKABLE QString getMusicPath(int id){
        return musicPath.at(id).filePath();
    }
    void run();



signals:
    void playlistChanged();

public slots:
private:
    QList<QFileInfo> musicPath;

};

#endif // PLAYLIST_H

playlist.cpp

#include "playlist.h"

PlayList::PlayList(QObject *parent) : QThread(parent)
{

}

PlayList::~PlayList()
{

}
void PlayList::findMusic(){
    this->start();
}

QJsonArray PlayList::playlist(){
    QJsonArray jsarr;
    QMutex mutex;
    mutex.lock();
    for(auto it:musicPath){
        QJsonObject obj;
        obj.insert("name",it.fileName());
        obj.insert("path","file://"+it.filePath());
        jsarr.append(obj);
    }
    mutex.unlock();
    return jsarr;
}
void PlayList::run(){
    QMutex mutex;
    mutex.lock();
    QString path="/mnt/sdcard";

    //get all files's filters
    QStringList filters;
    filters<<QString("*.mp3");

    musicPath.clear();

    //define iterator and filters
    QDirIterator dir_iterator(path, filters, QDir::Files | QDir::NoSymLinks,QDirIterator::Subdirectories);
    while(dir_iterator.hasNext())
    {
        dir_iterator.next();
        musicPath.append(dir_iterator.fileInfo());
//        qDebug()<<"name:"<<dir_iterator.fileInfo().fileName()<<"path:"<<dir_iterator.fileInfo().filePath();


    }
    mutex.unlock();
    playlistChanged();
}

效果图:

clipboard.png


tommego
21 声望23 粉丝

无限程式