Kivy - 播放器



Kivy 庫中的 VideoPlayer 元件是一個現成的控制元件,用於播放影片檔案並控制其播放和聲音。它是一個預定義的佈局,包含播放區域和用於播放/停止以及暫停/恢復播放的按鈕。它還有一個可以將播放位置移動到所需位置的進度條。

VideoPlayer 類在 "kivy.uix.videoplayer" 模組中定義。

from kivy.uix.videoplayer import VideoPlayer
player = VideoPlayer(**kwargs)

您需要使用表示要播放的影片檔案的字串為 VideoPlayer 物件的 source 屬性賦值。Kivy 支援不同的影片格式,包括 "mp4"、"avi" 和 "mpg"。

要開始播放影片,應將 state 屬性設定為 'play'。

from kivy.uix.videoplayer import VideoPlayer
player = VideoPlayer(source = "test.mp4")
player.state = 'play'

Kivy 的 VideoPlayer 的重要功能之一是能夠在影片中的特定位置顯示文字註釋,並在特定時間內顯示。註釋儲存在一個副檔名為 ".jsa" 的檔案中,並且與影片檔案同名。

.jsa 檔案是一種基於 JSON 的檔案格式。它包含註釋的起始位置、在螢幕上顯示的持續時間(以秒為單位)和註釋文字的值。

[
   {"start": 0, "duration": 2,
   "text": "Introduction"},
   {"start": 10, "duration": 5,
   "text": "Hello World"},
]

要使影片迴圈播放,請將 eos 選項設定為 loop −

options={'eos': 'loop'}

VideoPlayer 類定義了以下屬性 −

  • source − 要讀取的影片源。source 是一個 StringProperty,表示要播放的影片檔案的路徑。

  • state − 一個字串,指示是播放、暫停還是停止影片。state 是一個 OptionProperty,預設為 'stop'。

  • allow_fullscreen − 預設情況下,您可以雙擊影片使其全屏顯示。將此屬性設定為 False 以阻止此行為。

  • position − 影片在 0 到 duration 之間的位置。position 預設為 -1,並在影片載入時設定為實際位置。

  • seek(percent, precise=True) − 將位置更改為 duration 的百分比(嚴格來說,是比例)。percent 值應為浮點數或整數,介於 0-1 之間。precise 引數是一個布林值,預設為 True,其中精確查詢速度較慢,但查詢結果與請求的百分比完全一致。

  • thumbnail − 要顯示的影片縮圖。如果為 None,VideoPlayer 將嘗試從 source + '.png' 中查詢縮圖。

  • volume − 影片的音量,範圍為 0-1。1 表示最大音量,0 表示靜音。

  • annotation − VideoPlayer 使用 VideoPlayerAnnotation 物件根據儲存在 JSA 檔案中的 JSON 資料構建註釋。

以下鍵允許在 JSA 檔案中使用 −

  • start − 要顯示註釋的位置。

  • duration − 註釋標籤在播放器視窗上顯示的時間。

  • text − 要顯示為註釋的文字。

  • bgcolor − [r, g, b, a] - 文字框的背景顏色。

  • bgsource − 'filename' - 用於文字框背景的背景圖片。

  • border − (n, e, s, w) - 用於背景圖片的邊框。

示例

以下程式碼在應用程式視窗上呈現一個影片播放器元件 −

from kivy.app import App
from kivy.uix.videoplayer import VideoPlayer
from kivy.core.window import Window

Window.size = (720, 350)

class MainApp(App):
   title = "Simple Video"
   def build(self):
      player = VideoPlayer(
         source="video.mp4",
         size_hint=(0.8, 0.8),
         options={'fit_mode': 'contain'}
      )
      player.state = 'play'
      player.options = {'eos': 'loop'}
      player.allow_stretch = True
      return player
      
MainApp().run()

輸出

執行程式碼並檢查輸出 −

Kivy Video Player
廣告

© . All rights reserved.