qml多媒体

2023/8/2 qml

# 媒体播放

示例一

import QtQuick 2.0
import QtMultimedia

Window {
    width: 500;
    height: 300;
    visible: true
    title: qsTr("标题");
    MediaPlayer{
        id: mediaPlayer;
        source: "v.mp4";
        audioOutput: AudioOutput{}
        videoOutput: videoOutput
    }
    VideoOutput{
        id: videoOutput;
        anchors.fill: parent
    }

    MouseArea{
        anchors.fill: parent;
        onPressed: {
            mediaPlayer.play();
        }
    }
}

示例二:实现进度条

import QtQuick 2.0
import QtMultimedia

Window {
    width: 500;
    height: 300;
    visible: true
    title: qsTr("标题");
    MediaPlayer{
        id: player;
        source: "v.mp4";
        audioOutput: AudioOutput{}
        videoOutput: videoOutput
    }
    VideoOutput{
        id: videoOutput;
        anchors.fill: parent
    }

    MouseArea{
        anchors.fill: parent;
        onPressed: {
            player.play();
        }
    }
    // 进度条
    Rectangle{
        id: progressBar;
        height: 30;
        anchors.left: parent.left;
        anchors.right: parent.right;
        anchors.bottom: parent.bottom;
        color: "lightGray";
        Rectangle{
            anchors.left: parent.left;
            anchors.top: parent.top;
            anchors.bottom: parent.bottom;
            // 进度条位置
            width: player.duration>0?parent.width*player.position/player.duration:0;
            color: "darkGray"
        }

        MouseArea{
            anchors.fill: parent;
            onClicked: {
                if (player.seekable){
                    player.position = player.duration * mouse.x/width;
                }
            }
        }
    }
    Connections{
        target: player;
        onMediaObjectChanged:{
            if(player.mediaObject){
                player.mediaObject.notifyInterval = 50;
            }
        }
    }
}

# 视频流

import QtQuick 2.0
import QtMultimedia

Window {
    width: 500;
    height: 300;
    visible: true
    title: qsTr("标题");
    VideoOutput {
        id: videoOutput
        objectName: "videoOutput"
        anchors.fill: parent
        fillMode: VideoOutput.Stretch
    }

    // 创建视频会话
    CaptureSession {
        // 创建并选择相机
        camera: Camera {
            id: camera
            cameraDevice: mediaDevices.videoInputs[itm.cIndex] || mediaDevices.defaultVideoInput
        }
        // 与声明的视频输出组件作绑定
        videoOutput: videoOutput
        // 绑定完成启动相机
        onVideoOutputChanged: {
            camera.start()
        }
    }
}