BlackBerry 10使用Google TTS做中文文本朗读,开发语言C++ Qt Cascade

首先,我们测试一下Google TTS英文文本朗读

命令行测试:
wget -q -U Mozilla -O "helloworld.mp3" "http://translate.google.com/translate_tts?ie=UTF-8&tl=en&q=hello+world"


然后我们编写一段Qt代码,测试中文语音朗读,下载后的文件名叫 translate_tts,在手机该应用的data目录,比如

/accounts/1000/appdata/com.example.Hello1Standard.testDev_lo1Standard73e1edad/data


我们可以把这个mp3文件拷贝到BlackBerry 10的Windows网盘上面,然后把手机USB连接到PC机上,在PC机上播放。也可以在手机上用“音乐”程序直接播放。

cp translate_tts.mp3 /accounts/1000/shared/music/helloworld.mp3


Qt代码如下:

	/** 设置编码 begin  **/
	QTextCodec *codec = QTextCodec::codecForName("UTF-8");
	QTextCodec::setCodecForLocale(codec);
	QTextCodec::setCodecForCStrings(codec);
	QTextCodec::setCodecForTr(codec);
	/** 设置编码  end **/

    DownloadManager* downloader = new DownloadManager(&app);
    QString url = "http://translate.google.com/translate_tts?&tl=zh-CN&q=北京欢迎你";
    QUrl qurl = QUrl::fromEncoded(url.toLocal8Bit());
    downloader->SingleDownload(qurl);

DownloadManager.h头文件

#ifndef DOWNLOADMANAGER_H
#define DOWNLOADMANAGER_H

#include <QFile>
#include <QObject>
#include <QQueue>
#include <QTime>
#include <QUrl>
#include <QtNetwork/QNetworkAccessManager>

class DownloadManager: public QObject
{
    Q_OBJECT
public:
    DownloadManager(QObject *parent = 0);

    void append(const QUrl &url);
    void append(const QStringList &urlList);
    void SingleDownload(QUrl url);

signals:
    void finished();
    void progress(qint64 bytesReceived, qint64 bytesTotal, QString message);

private slots:
    void startNextDownload();
    void downloadProgress(qint64 bytesReceived, qint64 bytesTotal);
    void downloadFinished();
    void downloadReadyRead();

private:
    QString saveFileName(const QUrl &url);

    QNetworkAccessManager manager;
    QQueue<QUrl> downloadQueue;
    QNetworkReply *currentDownload;
    QString currentDownloadSaveFileName;
    QFile output;
    QTime downloadTime;

    int downloadedCount;
    int totalCount;
};

#endif


DownloadManager.cpp文件

#include "downloadmanager.h"

#include <QFileInfo>
#include <QtNetwork/QNetworkRequest>
#include <QtNetwork/QNetworkReply>
#include <QString>
#include <QStringList>
#include <QTimer>
#include <QDir>
#include <stdio.h>
#include <QEventLoop>

#include <QDebug>


DownloadManager::DownloadManager(QObject *parent)
    : QObject(parent), downloadedCount(0), totalCount(0)
{
}

void DownloadManager::append(const QStringList &urlList)
{
    foreach (QString url, urlList)
        append(QUrl::fromEncoded(url.toLocal8Bit()));

    if (downloadQueue.isEmpty())
        QTimer::singleShot(0, this, SIGNAL(finished()));
}

void DownloadManager::append(const QUrl &url)
{
    if (downloadQueue.isEmpty())
        QTimer::singleShot(0, this, SLOT(startNextDownload()));

    downloadQueue.enqueue(url);
    ++totalCount;
}

QString DownloadManager::saveFileName(const QUrl &url)
{
    QString modDir = "data";	//data is for BlackBerry 10 app, 使用相对目录
    QDir downloadDir(modDir);

    QString path = url.path();
    QString basename = modDir + "/" + QFileInfo(path).fileName();

    //如果下载url没有文件名,或者文件名后缀,则取名download
    if (basename.isEmpty())
        basename = "download";

    if (QFile::exists(basename)) {
        // already exists, don't overwrite
        int i = 0;
        basename += '.';
        while (QFile::exists(basename + QString::number(i)))
            ++i;

        basename += QString::number(i);
    }

    return basename;
}

void DownloadManager::startNextDownload()
{
    if (downloadQueue.isEmpty()) {
        printf("%d/%d files downloaded successfully\n", downloadedCount, totalCount);
        emit finished();
        return;
    }

    QUrl url = downloadQueue.dequeue();

    QString filename = saveFileName(url);
    qWarning("Downloading to: %s", filename.toLocal8Bit().data());
    output.setFileName(filename);
    if (!output.open(QIODevice::WriteOnly)) {
        fprintf(stderr, "Problem opening save file '%s' for download '%s': %s\n",
                qPrintable(filename), url.toEncoded().constData(),
                qPrintable(output.errorString()));

        startNextDownload();
        return;                 // skip this download
    }

    QNetworkRequest request(url);
    currentDownload = manager.get(request);
    connect(currentDownload, SIGNAL(downloadProgress(qint64,qint64)),
            SLOT(downloadProgress(qint64,qint64)));
    connect(currentDownload, SIGNAL(finished()),
            SLOT(downloadFinished()));
    connect(currentDownload, SIGNAL(readyRead()),
            SLOT(downloadReadyRead()));

    // prepare the output
    printf("Downloading %s...\n", url.toEncoded().constData());
    downloadTime.start();
}

void DownloadManager::SingleDownload(QUrl url) {
    QString filename = saveFileName(url) + ".mp3";
    qWarning("Downloading to: %s", filename.toLocal8Bit().data());
    qWarning("Downloading From: %s", url.path().toLocal8Bit().data());
    output.setFileName(filename);
    if (!output.open(QIODevice::WriteOnly)) {
        fprintf(stderr, "Problem opening save file '%s' for download '%s': %s\n",
                qPrintable(filename), url.toEncoded().constData(),
                qPrintable(output.errorString()));

        //startNextDownload();
        return;                 // skip this download
    }

    qWarning("Beginning Download");


    QNetworkRequest request;
    request.setUrl(url);
    currentDownload = manager.get(request);
    connect(currentDownload, SIGNAL(downloadProgress(qint64,qint64)),
			SLOT(downloadProgress(qint64,qint64)));
    connect(currentDownload, SIGNAL(finished()),
			SLOT(downloadFinished()));
    connect(currentDownload, SIGNAL(readyRead()),
            SLOT(downloadReadyRead()));

    //currentDownload->startTimer(1000);
    //currentDownload->open(QIODevice::ReadOnly);
    //currentDownload->request();
    downloadTime.start();
}

void DownloadManager::downloadProgress(qint64 bytesReceived, qint64 bytesTotal)
{
    //progressBar.setStatus(bytesReceived, bytesTotal);

    // calculate the download speed
    double speed = bytesReceived * 1000.0 / downloadTime.elapsed();
    QString unit;
    if (speed < 1024) {
        unit = "bytes/sec";
    } else if (speed < 1024*1024) {
        speed /= 1024;
        unit = "kB/s";
    } else {
        speed /= 1024*1024;
        unit = "MB/s";
    }

    QString spd = QString::number(speed);
    progress(bytesReceived, bytesTotal, "Downloading at: " + spd + unit);

    spd = "Downloading at: " + spd + unit;
    qDebug() << "Downloading at: " << spd  + " " + unit;
    qDebug() << bytesReceived << " bytes received";
    qDebug() <<  bytesTotal + " bytes Total.";
    //progressBar.setMessage(QString::fromLatin1("%1 %2")
                           //.arg(speed, 3, 'f', 1).arg(unit));
    //progressBar.update();
}

void DownloadManager::downloadFinished()
{
    //progressBar.clear();
    output.close();
    if (currentDownload->error()) {
        // download failed
        fprintf(stderr, "Failed: %s\n", qPrintable(currentDownload->errorString()));
    } else {
        printf("Succeeded.\n");
        ++downloadedCount;
    }

    qDebug() << "output file name " << output.fileName();
    currentDownloadSaveFileName = output.fileName();
    qWarning("downloadFinished");
    finished();

    currentDownload->deleteLater();
    startNextDownload();
}

void DownloadManager::downloadReadyRead()
{
	qWarning("downloadReadyRead");
    output.write(currentDownload->readAll());
}


参考:

google text-to-speech API及参考资料
http://hi.baidu.com/sjbh_blog/item/10844d3be0676ac5382ffa5e


downloadmanager应该是Nokia官方的例子代码,可以google一下 qt downloadmanager.h

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值