crossplatform.ru

Здравствуйте, гость ( Вход | Регистрация )


  Ответ в Phonon открытие видеофайла
Введите ваше имя
Подтвердите код

Введите в поле код из 6 символов, отображенных в виде изображения. Если вы не можете прочитать код с изображения, нажмите на изображение для генерации нового кода.
Теги
Выровнять по центру
Ссылка на тему
Ссылка на сообщение
Скрытый текст
Сокращение
Код с подсветкой
Offtopic
 
Удалить форматирование
Спец. элементы
Шрифт
Размер
 
Цвет шрифта
 
Отменить ввод
Вернуть ввод
Полужирный
Курсив
Подчеркнутый
 
 
Смайлики
Вставить изображение
Вставить адрес электронной почты
Цитата
Код
Раскрывающийся текст
 
Увеличить отступ
По левому краю
По центру
По правому краю
Вставить список
Вставить список

Опции сообщения
 Включить смайлы?
Иконки сообщения
(Опционально)
                                
                                
  [ Без иконки ]
 


Последние 10 сообщений [ в обратном порядке ]
Snikersoman Дата 9.12.2010, 17:31
  Разобрался-с таким кодоом все работает)
void PlayerWindow::openFile()
{
   wmp->setProperty("FileName",QApplication::applicationDirPath() + QDir::separator() + QLatin1String("1.avi"));  
}

Остался один вопрос как определить что видео закончилось. Спрашиваю потому что
connect( wmp, SIGNAL( finished() ),this, SLOT( videoend()) );
не работает а в консоле приложения вылетатет :
Object::connect: No such signal QAxWidget::finished()
Гость Дата 9.12.2010, 11:15
 
Цитата(Snikersoman @ 7.12.2010, 19:02) *
wmp->setProperty("dfgdg",QApplication::applicationDirPath() + QDir::separator() + QLatin1String("1.avi"));

Для начало разберитесь с СОМ-объектом, что это такое и какие свойства у него есть. Сомнительно что в СОМ медиаплейра есть свойство "dfgdg".
Для примера: если тебе скажут "Отреж себе dfgdg", ты что себе отрежешь?
Snikersoman Дата 7.12.2010, 19:02
  В мою программу пришлось внести некоторые модификации, в институте так не хотят принимать...(
Поэтому я с помощью QAxWidget прикрутил Windows Media Player . Вот исходники такого плеера если кому нужен
mediaplayer.pro
Раскрывающийся текст
TEMPLATE      = app
CONFIG       += qaxcontainer
HEADERS       = playerwindow.h
SOURCES       = main.cpp \
                playerwindow.cpp

mediaplayer.h
Раскрывающийся текст
#ifndef PLAYERWINDOW_H
#define PLAYERWINDOW_H

#include <QWidget>

class QAxWidget;
class QSlider;
class QToolButton;

class PlayerWindow 
: public QWidget
{
    Q_OBJECT
    Q_ENUMS(ReadyStateConstants)

public:
    enum PlayStateConstants { Stopped = 0, Paused = 1, Playing = 2 };
    enum ReadyStateConstants { Uninitialized = 0, Loading = 1,
                               Interactive = 3, Complete = 4 };

    PlayerWindow();

protected:
    void timerEvent(QTimerEvent *event);

private slots:
    void onPlayStateChange(int oldState, int newState);
    void onReadyStateChange(ReadyStateConstants readyState);
    void onPositionChange(double oldPos, double newPos);
    void sliderValueChanged(int newValue);
    void openFile();

private:
    QAxWidget *wmp;
    QToolButton *openButton;
    QToolButton *playPauseButton;
    QToolButton *stopButton;
    QSlider *seekSlider;
    QString fileFilters;
    int updateTimer;
};

#endif

mediaplayer.cpp
Раскрывающийся текст
#include <QtGui>
#include <QAxWidget>

#include "playerwindow.h"

PlayerWindow::PlayerWindow()
{
    wmp = new QAxWidget;
    wmp->setControl("{22D6F312-B0F6-11D0-94AB-0080C74C7E95}");
    wmp->setProperty("ShowControls", false);
    wmp->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    connect(wmp, SIGNAL(PlayStateChange(int, int)),
            this, SLOT(onPlayStateChange(int, int)));
    connect(wmp, SIGNAL(ReadyStateChange(ReadyStateConstants)),
            this, SLOT(onReadyStateChange(ReadyStateConstants)));
    connect(wmp, SIGNAL(PositionChange(double, double)),
            this, SLOT(onPositionChange(double, double)));

    openButton = new QToolButton;
    openButton->setText(tr("&Open..."));
    connect(openButton, SIGNAL(clicked()), this, SLOT(openFile()));

    playPauseButton = new QToolButton;
    playPauseButton->setText(tr("&Play"));
    playPauseButton->setEnabled(false);
    connect(playPauseButton, SIGNAL(clicked()), wmp, SLOT(Play()));

    stopButton = new QToolButton;
    stopButton->setText(tr("&Stop"));
    stopButton->setEnabled(false);
    connect(stopButton, SIGNAL(clicked()), wmp, SLOT(Stop()));

    seekSlider = new QSlider(Qt::Horizontal);
    seekSlider->setEnabled(false);
    connect(seekSlider, SIGNAL(valueChanged(int)),
            this, SLOT(sliderValueChanged(int)));
    connect(seekSlider, SIGNAL(sliderPressed()),
            wmp, SLOT(Pause()));

    fileFilters = tr("Video files (*.mpg *.mpeg *.avi *.wmv)\n"
                     "Audio files (*.mp3 *.wav)");
    updateTimer = 0;

    QHBoxLayout *buttonLayout = new QHBoxLayout;
    buttonLayout->addWidget(openButton);
    buttonLayout->addWidget(playPauseButton);
    buttonLayout->addWidget(stopButton);

    QVBoxLayout *mainLayout = new QVBoxLayout;
    mainLayout->addWidget(wmp);
    mainLayout->addLayout(buttonLayout);
    mainLayout->addWidget(seekSlider);
    setLayout(mainLayout);

    setWindowTitle(tr("Media Player"));
    setMouseTracking(true);
}

void PlayerWindow::timerEvent(QTimerEvent *event)
{
    if (event->timerId() == updateTimer) {
        double curPos = wmp->property("CurrentPosition").toDouble();
        onPositionChange(-1, curPos);
    } else {
        QWidget::timerEvent(event);
    }
}

void PlayerWindow::onPlayStateChange(int, int newState)
{
    playPauseButton->disconnect(wmp);

    switch (newState) {
    case Stopped:
        if (updateTimer) {
            killTimer(updateTimer);
            updateTimer = 0;
        }
        // fall through
    case Paused:
        connect(playPauseButton, SIGNAL(clicked()), wmp, SLOT(Play()));
        stopButton->setEnabled(false);
        playPauseButton->setText(tr("&Play"));
        break;
    case Playing:
        if (!updateTimer)
            updateTimer = startTimer(100);
        connect(playPauseButton, SIGNAL(clicked()),
                wmp, SLOT(Pause()));
        stopButton->setEnabled(true);
        playPauseButton->setText(tr("&Pause"));
    }
}

void PlayerWindow::onReadyStateChange(ReadyStateConstants ready)
{
    if (ready == Complete) {
        double duration = 60 * wmp->property("Duration").toDouble();
        seekSlider->setMinimum(0);
        seekSlider->setMaximum(int(duration));
        seekSlider->setEnabled(true);
        playPauseButton->setEnabled(true);
    }
}

void PlayerWindow::onPositionChange(double, double newPos)
{
    seekSlider->blockSignals(true);
    seekSlider->setValue(int(newPos * 60));
    seekSlider->blockSignals(false);
}

void PlayerWindow::sliderValueChanged(int newValue)
{
    seekSlider->blockSignals(true);
    wmp->setProperty("CurrentPosition", double(newValue) / 60);
    seekSlider->blockSignals(false);
}

void PlayerWindow::openFile()
{
    QString fileName = QFileDialog::getOpenFileName(this,
                               tr("Select File"), ".", fileFilters);
    if (!fileName.isEmpty())
        wmp->setProperty("FileName",
                         QDir::toNativeSeparators(fileName));
}

main.cpp
Раскрывающийся текст
#include <QApplication>

#include "playerwindow.h"

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    PlayerWindow playerWin;
    playerWin.show();
    return app.exec();
}

Столкнулся с такой вещью: не работает метод открытия файла с диска который я применял в Phononе
Phonon:
void Form::selectfile(){
ui->openButton->setEnabled(false);
    ui->videoPlayer->play(QApplication::applicationDirPath() + QDir::separator() + QLatin1String("1.avi"));
}

QAxWidget:
void PlayerWindow::openFile()
{
   /// QString fileName = QFileDialog::getOpenFileName(this,
                             ///  tr("Select File"), ".", fileFilters);
   /// if (!fileName.isEmpty())
    ///    wmp->setProperty("FileName",
                    ///     QDir::toNativeSeparators(fileName));
    wmp->setProperty("dfgdg",QApplication::applicationDirPath() + QDir::separator() + QLatin1String("1.avi"));  
/// wmp->Play(QApplication::applicationDirPath() + QDir::separator() + QLatin1String("1.avi")); //не работает совсем
}

Вот эта строка должна все решать программа с ней компилируется но при нажатии на кнопку видеофайл не открывается
 wmp->setProperty("dfgdg",QApplication::applicationDirPath() + QDir::separator() + QLatin1String("1.avi"));

Что я делаю не так?
Snikersoman Дата 4.12.2010, 22:55
 
Цитата(igor_bogomolov @ 4.12.2010, 21:22) *
Сделайте так и будет счастье

Черт до чего же приятно когда тебе подсказываю рабочее решение...:)
Счастье да и только:)
igor_bogomolov Дата 4.12.2010, 21:22
  Смотрите внимательнее документацию, play не может принимать const char*, а во вторых нужно указывать полный путь до файла.
Сделайте так и будет счастье
player->play(QApplication::applicationDirPath() + QDir::separator() + QLatin1String("1.avi"));
Snikersoman Дата 4.12.2010, 20:27
  Доброго времени суток господа программисты пишу вам по такому вопросу: у меня в программе есть видео плеер и требуется чтобы по нажатии кнопки плеер начал воспроизводить определенный видеофайл (лежит у экзешника). Тоесть сам без стандартного окошка выбора файла. Вот листинг видео плеера который я взял за основу:
Video.pro
Раскрывающийся текст
######################################################################
# Automatically generated by qmake (2.01a) ?? 14. ??? 21:28:46 2008
######################################################################

TEMPLATE = app
TARGET = 
DEPENDPATH += .
INCLUDEPATH += .
QT += phonon

# Input
HEADERS += mainwin.h
SOURCES += main.cpp mainwin.cpp

mainwin.h
Раскрывающийся текст
#ifndef _MAINWIN_H_
#define _MAINWIN_H_

#include <QtGui>
#include <phonon>

// using namespace Phonon;

class Mainwin : public QMainWindow {
        Q_OBJECT
public:
        Mainwin();
private slots:
        void selectfile();
        void playfile();
        void setvolume(int);
private:
        Phonon::VideoPlayer *player;
        QToolBar *toolbar;
        QPushButton *openbutton, *playbutton, *pausebutton, *stopbutton;
        QSlider *volumeslider;
        Phonon::SeekSlider *seekslider;

};
#endif // _MAINWIN_H_

main.cpp
Раскрывающийся текст
#include <QtGui>
#include <mainwin.h>

int main(int argv, char **args){
    QApplication app(argv, args);
    app.setApplicationName("Video Player");
    Mainwin win;
    win.show();
    return app.exec();
}

mainwin.cpp
Раскрывающийся текст
#include <QtGui>
#include "mainwin.h"

Mainwin::Mainwin(){
    QWidget *widget = new QWidget(this);
    QVBoxLayout *lay = new QVBoxLayout(widget);
    
    player = new Phonon::VideoPlayer(Phonon::VideoCategory);
    lay->addWidget(player, 1);
    
    seekslider = new Phonon::SeekSlider;
    seekslider->setMediaObject(player->mediaObject());
    lay->addWidget(seekslider, 0);
    
    toolbar = addToolBar(tr("toolbar"));
    
    openbutton = new QPushButton(tr("Open"), toolbar);
    toolbar->addWidget(openbutton);
    connect(openbutton, SIGNAL(clicked()), this, SLOT(selectfile()));
    
    playbutton = new QPushButton(tr("Play"), toolbar);
    toolbar->addWidget(playbutton);
    connect(playbutton, SIGNAL(clicked()), this, SLOT(playfile()));
    
    stopbutton = new QPushButton(tr("Stop"), toolbar);
    toolbar->addWidget(stopbutton);
    connect(stopbutton, SIGNAL(clicked()), player, SLOT(stop()));
    
    pausebutton = new QPushButton(tr("Pause"), toolbar);
    toolbar->addWidget(pausebutton);
    connect(pausebutton, SIGNAL(clicked()), player, SLOT(pause()));
    
    volumeslider = new QSlider(Qt::Horizontal, toolbar);
    volumeslider->setRange(0, 100);
    volumeslider->setValue(100);
    connect(volumeslider, SIGNAL(valueChanged(int)), this,
            SLOT(setvolume(int)));
    toolbar->addWidget(volumeslider);
    
    widget->setLayout(lay);
    setCentralWidget(widget);
}

void Mainwin::selectfile(){
    QString filename = QFileDialog::getOpenFileName(
        this, tr("Select video file"), ".");

    if (filename.isEmpty())
        return;

    player->play(filename);
    resize(sizeHint());
}

void Mainwin::playfile(){
    player->play();
    resize(sizeHint());
}

void Mainwin::setvolume(int value){
    float volume;
    volume = (static_cast<float>(value)) / 100;
    player->setVolume(volume);
}

Данный плеер рабочий и свои функции он выполняет, мне кажется что если заменить в этой части
void Mainwin::selectfile(){
    QString filename = QFileDialog::getOpenFileName(
        this, tr("Select video file"), ".");

    if (filename.isEmpty())
        return;

    player->play(filename);
    resize(sizeHint());
}

Переменную filename на название искомого файла или же просто вписать вместо нее название то я получу то что мне нужно:
void Mainwin::playfile(){
    player->play("1.avi");
    resize(sizeHint());
}

пробовал так однако нефига не получается((( Думаю из за того что действую в корне не верно...
Посему вопрос: как это реализовать?
Просмотр темы полностью (откроется в новом окне)
RSS Рейтинг@Mail.ru Текстовая версия Сейчас: 11.7.2025, 19:55