Recherche avancée

Médias (91)

Autres articles (35)

  • Personnaliser en ajoutant son logo, sa bannière ou son image de fond

    5 septembre 2013, par

    Certains thèmes prennent en compte trois éléments de personnalisation : l’ajout d’un logo ; l’ajout d’une bannière l’ajout d’une image de fond ;

  • Ecrire une actualité

    21 juin 2013, par

    Présentez les changements dans votre MédiaSPIP ou les actualités de vos projets sur votre MédiaSPIP grâce à la rubrique actualités.
    Dans le thème par défaut spipeo de MédiaSPIP, les actualités sont affichées en bas de la page principale sous les éditoriaux.
    Vous pouvez personnaliser le formulaire de création d’une actualité.
    Formulaire de création d’une actualité Dans le cas d’un document de type actualité, les champs proposés par défaut sont : Date de publication ( personnaliser la date de publication ) (...)

  • Publier sur MédiaSpip

    13 juin 2013

    Puis-je poster des contenus à partir d’une tablette Ipad ?
    Oui, si votre Médiaspip installé est à la version 0.2 ou supérieure. Contacter au besoin l’administrateur de votre MédiaSpip pour le savoir

Sur d’autres sites (6437)

  • Youtube automatic creating and starting live stream with ffmpeg Python

    20 août 2023, par MrKolia1_1

    I'm trying to create a new broadcast on the channel and then start the stream so that the video is broadcast, the problem is that I can't start the broadcast after it is created, it is in the scheduled, how can I start the broadcast ?

    


    enter image description here

    


    import datetime
import json
import os
import threading
import time

import cv2
import subprocess
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build

APP_TOKEN_FILE = "client_secret.json"
USER_TOKEN_FILE = "user_token.json"

SCOPES = [
    'https://www.googleapis.com/auth/youtube.force-ssl',
    'https://www.googleapis.com/auth/userinfo.profile',
]


def get_stream_info(stream_id):
    creds = get_creds_saved()
    service = build('youtube', 'v3', credentials=creds)

    request = service.liveBroadcasts().list(
        part='snippet,contentDetails,status',
        id=stream_id
    )

    response = request.execute()

    if 'items' in response and len(response['items']) > 0:
        return response['items'][0]
    else:
        return None


def get_creds_cons():
    # Create credentials via console flow
    flow = InstalledAppFlow.from_client_secrets_file(APP_TOKEN_FILE, SCOPES)
    return flow.run_console()


def get_creds_saved():
    creds = None

    if os.path.exists(USER_TOKEN_FILE):
        # Load user credentials from a saved file
        creds = Credentials.from_authorized_user_file(USER_TOKEN_FILE, SCOPES)

    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            # Create new credentials via local server flow
            flow = InstalledAppFlow.from_client_secrets_file(APP_TOKEN_FILE, SCOPES)
            creds = flow.run_local_server(port=0)

        with open(USER_TOKEN_FILE, 'w') as token:
            token.write(creds.to_json())

    return creds


def get_service():
    # Get YouTube API service using credentials
    creds = get_creds_saved()
    service = build('youtube', 'v3', credentials=creds)
    return service


def create_live_stream(title, description):
    service = get_service()
    scheduled_start_time = datetime.datetime.utcnow().isoformat()

    request = service.liveBroadcasts().insert(
        part="snippet,status,contentDetails",
        body={
            "snippet": {
                "title": title,
                "description": description,
                "scheduledStartTime": scheduled_start_time,
            },
            "status": {
                "privacyStatus": "private",
                "lifeCycleStatus": "ready",
                "recordingStatus": "notRecording",
                "selfDeclaredMadeForKids": False
            },
            "contentDetails": {
                "enableAutoStart": False
            }
        }
    )
    response = request.execute()
    return response['id']


def stream_video(video_path, stream_key):
    args = [
        '-re',
        '-i', video_path,
        '-c:v', 'libx264',
        '-preset', 'veryfast',
        '-c:a', 'aac',
        '-f', 'flv',
        f'rtmp://a.rtmp.youtube.com/live2/{stream_key}'
    ]

    subprocess.run(['ffmpeg'] + args)


def get_scheduled_stream_info(stream_id):
    creds = get_creds_saved()
    service = build('youtube', 'v3', credentials=creds)

    request = service.liveBroadcasts().list(
        part='snippet,status',
        id=stream_id
    )

    response = request.execute()

    if 'items' in response and len(response['items']) > 0:
        return response['items'][0]
    else:
        return None



if __name__ == '__main__':
    print("** Hello, Azzrael_YT subscribers!!!\n")

    strId = create_live_stream("tittle", "description")
    pretty_json = json.dumps(get_scheduled_stream_info(strId), indent=4)

    print(pretty_json)

    # Stream video
    video_path = "C:/Users/admin/PycharmProjects/pythonProject/video.mp4"  # Update this with your video file path
    stream_key = 'dh9z-jtkx-wbq3-6wvp-2tac'  # Replace with your YouTube stream key
    video_thread = threading.Thread(target=stream_video, args=(video_path, stream_key))
    #video_thread.start()



    


    json responce info from created stream :
,
"scheduledStartTime" : "2023-08-20T10:51:22Z",
"isDefaultBroadcast" : false,
"liveChatId" : "KicKGFVDZ01UNS1CLVNfV0FJencxVXY4cC1ZQRILSG9QU0RJZ2hQMkE"
,
"status" : 
"lifeCycleStatus" : "created",
"privacyStatus" : "private",
"recordingStatus" : "notRecording",
"madeForKids" : false,
"selfDeclaredMadeForKids" : false



    


  • FFMPEG : TS video copied to MP4, missing 3 first frames [closed]

    21 août 2023, par Vasilis Lemonidis

    Running :

    


    ffmpeg -i test.ts -fflags +genpts -c copy -y test.mp4


    


    for this test.ts, which has 30 frames, readable by opencv, I end up with 28 frames, out of which 27 are readable by opencv. More specifically :

    


    ffprobe -v error -select_streams v:0 -count_packets  -show_entries stream=nb_read_packets -of csv=p=0 tmp.ts 


    


    returns 30.

    


    ffprobe -v error -select_streams v:0 -count_packets     -show_entries stream=nb_read_packets -of csv=p=0 tmp.mp4


    


    returns 28.

    


    Using OpenCV in that manner

    


    cap = cv2.VideoCapture(tmp_path)
readMat = []
while cap.isOpened():
        ret, frame = cap.read()
        if not ret:
            break
        readMat.append(frame)


    


    I get for the ts file 30 frames, while for the mp4 27 frames.

    


    Could someone explain why the discrepancies ? I get no error during the transformation from ts to mp4 :

    


    ffmpeg version N-111746-gd53acf452f Copyright (c) 2000-2023 the FFmpeg developers
  built with gcc 11.3.0 (GCC)
  configuration: --ld=g++ --bindir=/bin --extra-libs='-lpthread -lm' --pkg-config-flags=--static --enable-static --enable-gpl --enable-libaom --enable-libass --enable-libfreetype --enable-libmp3lame --enable-libopus --enable-libsvtav1 --enable-libdav1d --enable-libvorbis --enable-libvpx --enable-libx264 --enable-libx265 --enable-nonfree --enable-cuda-nvcc --enable-cuvid --enable-nvenc --enable-libnpp 
  libavutil      58. 16.101 / 58. 16.101
  libavcodec     60. 23.100 / 60. 23.100
  libavformat    60. 10.100 / 60. 10.100
  libavdevice    60.  2.101 / 60.  2.101
  libavfilter     9. 10.100 /  9. 10.100
  libswscale      7.  3.100 /  7.  3.100
  libswresample   4. 11.100 /  4. 11.100
  libpostproc    57.  2.100 / 57.  2.100
[mpegts @ 0x4237240] DTS discontinuity in stream 0: packet 5 with DTS 306003, packet 6 with DTS 396001
Input #0, mpegts, from 'tmp.ts':
  Duration: 00:00:21.33, start: 3.400000, bitrate: 15 kb/s
  Program 1 
    Metadata:
      service_name    : Service01
      service_provider: FFmpeg
  Stream #0:0[0x100]: Video: h264 (High) ([27][0][0][0] / 0x001B), yuv420p(progressive), 300x300, 1 fps, 3 tbr, 90k tbn
Output #0, mp4, to 'test.mp4':
  Metadata:
    encoder         : Lavf60.10.100
  Stream #0:0: Video: h264 (High) (avc1 / 0x31637661), yuv420p(progressive), 300x300, q=2-31, 1 fps, 3 tbr, 90k tbn
Stream mapping:
  Stream #0:0 -> #0:0 (copy)
Press [q] to stop, [?] for help
[out#0/mp4 @ 0x423e280] video:25kB audio:0kB subtitle:0kB other streams:0kB global headers:0kB muxing overhead: 4.192123%
frame=   30 fps=0.0 q=-1.0 Lsize=      26kB time=00:00:21.00 bitrate=  10.3kbits/s speed=1e+04x 


    


    Additional information

    


    The origin of the video I am processing comes from a continuous stitching operation of still images ts videos, produced by this class update method :

    


    import cv2
import os
import subprocess
from tempfile import NamedTemporaryFile
class VideoUpdater:
    def __init__(
        self, video_path: str, framerate: int, timePerFrame: Optional[int] = None
    ):
        """
        Video updater takes in a video path, and updates it using a supplied frame, based on a given framerate.
        Args:
            video_path: str: Specify the path to the video file
            framerate: int: Set the frame rate of the video
        """
        if not video_path.endswith(".mp4"):
            LOGGER.warning(
                f"File type {os.path.splitext(video_path)[1]} not supported for streaming, switching to ts"
            )
            video_path = os.path.splitext(video_path)[0] + ".mp4"

        self._ps = None
        self.env = {
            
        }
        self.ffmpeg = "/usr/bin/ffmpeg "

        self.video_path = video_path
        self.ts_path = video_path.replace(".mp4", ".ts")
        self.tfile = None
        self.framerate = framerate
        self._video = None
        self.last_frame = None
        self.curr_frame = None


    def update(self, frame: np.ndarray):
        if len(frame.shape) == 2:
            frame = cv2.cvtColor(frame, cv2.COLOR_GRAY2BGR)
        else:
            frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)
        self.writeFrame(frame)

    def writeFrame(self, frame: np.ndarray):
        """
        The writeFrame function takes a frame and writes it to the video file.
        Args:
            frame: np.ndarray: Write the frame to a temporary file
        """


        tImLFrame = NamedTemporaryFile(suffix=".png")
        tVidLFrame = NamedTemporaryFile(suffix=".ts")

        cv2.imwrite(tImLFrame.name, frame)
        ps = subprocess.Popen(
            self.ffmpeg
            + rf"-loop 1 -r {self.framerate} -i {tImLFrame.name} -t {self.framerate} -vcodec libx264 -pix_fmt yuv420p -y {tVidLFrame.name}",
            env=self.env,
            shell=True,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
        )
        ps.communicate()
        if os.path.isfile(self.ts_path):
            # this does not work to watch, as timestamps are not updated
            ps = subprocess.Popen(
                self.ffmpeg
                + rf'-i "concat:{self.ts_path}|{tVidLFrame.name}" -c copy -y {self.ts_path.replace(".ts", ".bak.ts")}',
                env=self.env,
                shell=True,
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
            )
            ps.communicate()
            shutil.move(self.ts_path.replace(".ts", ".bak.ts"), self.ts_path)

        else:
            shutil.copyfile(tVidLFrame.name, self.ts_path)
        # fixing timestamps, we dont have to wait for this operation
        ps = subprocess.Popen(
            self.ffmpeg
            + rf"-i {self.ts_path} -fflags +genpts -c copy -y {self.video_path}",
            env=self.env,
            shell=True,
            # stdout=subprocess.PIPE,
            # stderr=subprocess.PIPE,
        )
        tImLFrame.close()
        tVidLFrame.close()


    


  • FileNotFoundError when extracting audio from recently saved video using FFMPEG"

    3 août 2023, par Peter Long

    Scenario : I'm using this tool to record tiktok live. I write another script to call the main.pytool because I want to add some additional options, for example, to extract the audio of the live video that is recorded

    


    FFMPEG is used to extract the audio. First the video is saved (with FFMPEG) and after I want to extract the audio of that video (again with FFMPEG). The path where the video is recorded and saved is C:\Users\Administrator\Desktop\tiktok

    


    The problem is that I see the file and it is saved, but this error is generated as output : FileNotFoundError: [WinError 2] The system cannot find the file specified

    


    I can't figure out why it doesn't detect the last saved video file in general

    


    I try with this

    


    import os
import subprocess
import time
from moviepy.editor import VideoFileClip

def main():
    # Command to run main.py and record the video
    cmd = 'python main.py -user ryzebenny -output "C:\\Users\\Administrator\\Desktop\\tiktok" -ffmpeg -duration 30 --auto-convert'
    subprocess.run(cmd, shell=True)

    # Wait for the video file to appear in the folder
    wait_for_video("C:\\Users\\Administrator\\Desktop\\tiktok")

    # Extract audio from recorded video
    video_filename = find_latest_file("C:\\Users\\Administrator\\Desktop\\tiktok", ".mp4")
    if video_filename:
        video_path = os.path.join("C:\\Users\\Administrator\\Desktop\\tiktok", video_filename)
        audio_filename = video_filename.replace(".mp4", ".mp3")
        audio_path = os.path.join("C:\\Users\\Administrator\\Desktop\\tiktok", audio_filename)

        video_clip = VideoFileClip(video_path)
        audio_clip = video_clip.audio
        audio_clip.write_audiofile(audio_path)
        audio_clip.close()
        video_clip.close()
        print(f"Audio extraction completed: {audio_filename}")
    else:
        print("No video files found.")

def wait_for_video(directory):
    max_wait_time = 60  # Maximum time to wait in seconds
    start_time = time.time()
    while time.time() - start_time < max_wait_time:
        if find_latest_file(directory, ".mp4"):
            break
        time.sleep(1)

def find_latest_file(directory, extension):
    list_of_files = [f for f in os.listdir(directory) if f.endswith(extension) and os.path.isfile(os.path.join(directory, f))]
    if list_of_files:
        return max(list_of_files, key=os.path.getctime)
    return None

if __name__ == "__main__":
    main()


    


    but i get this error

    


    [*] 2023-08-03 15:57:09 - INFO - START RECORDING FOR 30 SECONDS&#xA;[*] 2023-08-03 15:57:09 - INFO - [PRESS &#x27;q&#x27; TO STOP RECORDING]&#xA;[*] 2023-08-03 15:57:31 - INFO - FINISH: C:\Users\Administrator\Desktop\tiktok\TK_ryzebenny_2023.08.03_15-57-09_flv.mp4&#xA;&#xA;Traceback (most recent call last):&#xA;  File "C:\Users\Administrator\Desktop\tiktok\TikTok-Live-Recorder\run_main.py", line 45, in <module>&#xA;    main()&#xA;  File "C:\Users\Administrator\Desktop\tiktok\TikTok-Live-Recorder\run_main.py", line 12, in main&#xA;    wait_for_video("C:\\Users\\Administrator\\Desktop\\tiktok")&#xA;  File "C:\Users\Administrator\Desktop\tiktok\TikTok-Live-Recorder\run_main.py", line 34, in wait_for_video&#xA;    if find_latest_file(directory, ".mp4"):&#xA;       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^&#xA;  File "C:\Users\Administrator\Desktop\tiktok\TikTok-Live-Recorder\run_main.py", line 41, in find_latest_file&#xA;    return max(list_of_files, key=os.path.getctime)&#xA;           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^&#xA;  File "<frozen genericpath="genericpath">", line 65, in getctime&#xA;FileNotFoundError: [WinError 2] The system cannot find the file specified: &#x27;TK_ryzebenny_2023.08.03_15-57-09.mp4&#x27;&#xA;</frozen></module>

    &#xA;

    Instead, I expect that once I save the video (in .mp4) the audio of that video will be extracted afterwards

    &#xA;