Recherche avancée

Médias (1)

Mot : - Tags -/belgique

Autres articles (85)

  • Installation en mode ferme

    4 février 2011, par

    Le mode ferme permet d’héberger plusieurs sites de type MediaSPIP en n’installant qu’une seule fois son noyau fonctionnel.
    C’est la méthode que nous utilisons sur cette même plateforme.
    L’utilisation en mode ferme nécessite de connaïtre un peu le mécanisme de SPIP contrairement à la version standalone qui ne nécessite pas réellement de connaissances spécifique puisque l’espace privé habituel de SPIP n’est plus utilisé.
    Dans un premier temps, vous devez avoir installé les mêmes fichiers que l’installation (...)

  • Organiser par catégorie

    17 mai 2013, par

    Dans MédiaSPIP, une rubrique a 2 noms : catégorie et rubrique.
    Les différents documents stockés dans MédiaSPIP peuvent être rangés dans différentes catégories. On peut créer une catégorie en cliquant sur "publier une catégorie" dans le menu publier en haut à droite ( après authentification ). Une catégorie peut être rangée dans une autre catégorie aussi ce qui fait qu’on peut construire une arborescence de catégories.
    Lors de la publication prochaine d’un document, la nouvelle catégorie créée sera proposée (...)

  • Récupération d’informations sur le site maître à l’installation d’une instance

    26 novembre 2010, par

    Utilité
    Sur le site principal, une instance de mutualisation est définie par plusieurs choses : Les données dans la table spip_mutus ; Son logo ; Son auteur principal (id_admin dans la table spip_mutus correspondant à un id_auteur de la table spip_auteurs)qui sera le seul à pouvoir créer définitivement l’instance de mutualisation ;
    Il peut donc être tout à fait judicieux de vouloir récupérer certaines de ces informations afin de compléter l’installation d’une instance pour, par exemple : récupérer le (...)

Sur d’autres sites (5490)

  • "FFmpeg : Error not transitioning to the next song in Discord Bot's queue."

    1er avril 2024, par noober

    I have 3 modules, but I'm sure the error occurs within this module, and here is the entire code within that module :

    


    import asyncio
import discord
from discord import FFmpegOpusAudio, Embed
import os

async def handle_help(message):
    embed = discord.Embed(
        title="Danh sách lệnh cho Bé Mèo",
        description="Dưới đây là các lệnh mà chủ nhân có thể bắt Bé Mèo phục vụ:",
        color=discord.Color.blue()
    )
    embed.add_field(name="!play", value="Phát một bài hát từ YouTube.", inline=False)
    embed.add_field(name="!pause", value="Tạm dừng bài hát đang phát.", inline=False)
    embed.add_field(name="!resume", value="Tiếp tục bài hát đang bị tạm dừng.", inline=False)
    embed.add_field(name="!skip", value="Chuyển đến bài hát tiếp theo trong danh sách chờ.", inline=False)
    embed.add_field(name="!stop", value="Dừng phát nhạc và cho phép Bé Mèo đi ngủ tiếp.", inline=False)
    # Thêm các lệnh khác theo cùng mẫu trên
    await message.channel.send(embed=embed)

class Song:
    def __init__(self, title, player):
        self.title = title  # Lưu trữ tiêu đề bài hát ở đây
        self.player = player

# Thêm đối tượng Song vào hàng đợi
def add_song_to_queue(guild_id, queues, song):
    queues.setdefault(guild_id, []).append(song)

async def handle_list(message, queues):
    log_file_path = "C:\\Bot Music 2\\song_log.txt"
    if os.path.exists(log_file_path):
        with open(log_file_path, "r", encoding="utf-8") as f:
            song_list = f.readlines()

        if song_list:
            embed = discord.Embed(
                title="Danh sách bài hát",
                description="Danh sách các bài hát đã phát:",
                color=discord.Color.blue()
            )

            for i, song in enumerate(song_list, start=1):
                if i == 1:
                    song = "- Đang phát: " + song.strip()
                embed.add_field(name=f"Bài hát {i}", value=song, inline=False)

            await message.channel.send(embed=embed)
        else:
            await message.channel.send("Hiện không có dữ liệu trong file log.")
    else:
        await message.channel.send("File log không tồn tại.")

async def handle_commands(message, client, queues, voice_clients, yt_dl_options, ytdl, ffmpeg_options=None, guild_id=None, data=None):
    # Nếu không có ffmpeg_options, sử dụng các thiết lập mặc định
    if ffmpeg_options is None:
        ffmpeg_options = {
            'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5',
            'options': '-vn -filter:a "volume=0.25"'
        }
    
    # Khởi tạo voice_client
    if guild_id is None:
        guild_id = message.guild.id

    if guild_id in voice_clients:
        voice_client = voice_clients[guild_id]
    else:
        voice_client = None

    # Xử lý lệnh !play
    if message.content.startswith("!play"):
        try:
            # Kiểm tra xem người gửi tin nhắn có đang ở trong kênh voice không
            voice_channel = message.author.voice.channel
            # Kiểm tra xem bot có đang ở trong kênh voice của guild không
            if voice_client and voice_client.is_connected():
                await voice_client.move_to(voice_channel)
            else:
                voice_client = await voice_channel.connect()
                voice_clients[guild_id] = voice_client
        except Exception as e:
            print(e)

        try:
            query = ' '.join(message.content.split()[1:])
            if query.startswith('http'):
                url = query
            else:
                query = 'ytsearch:' + query
                loop = asyncio.get_event_loop()
                data = await loop.run_in_executor(None, lambda: ytdl.extract_info(query, download=False))
                if not data:
                    raise ValueError("Không có dữ liệu trả về từ YouTube.")
                url = data['entries'][0]['url']

            player = FFmpegOpusAudio(url, **ffmpeg_options)
            # Lấy thông tin của bài hát mới đang được yêu cầu
            title = data['entries'][0]['title']
            duration = data['entries'][0]['duration']
            creator = data['entries'][0]['creator'] if 'creator' in data['entries'][0] else "Unknown"
            requester = message.author.nick if message.author.nick else message.author.name
                    
            # Tạo embed để thông báo thông tin bài hát mới
            embed = discord.Embed(
                title="Thông tin bài hát mới",
                description=f"**Bài hát:** *{title}*\n**Thời lượng:** *{duration}*\n**Tác giả:** *{creator}*\n**Người yêu cầu:** *{requester}*",
                color=discord.Color.green()
            )
            await message.channel.send(embed=embed)
            
            # Sau khi lấy thông tin của bài hát diễn ra, gọi hàm log_song_title với title của bài hát
            # Ví dụ:
            title = data['entries'][0]['title']
            await log_song_title(title)

            # Thêm vào danh sách chờ nếu có bài hát đang phát
            if voice_client.is_playing():
                queues.setdefault(guild_id, []).append(player)
            else:
                voice_client.play(player)
                
        except Exception as e:
            print(e)
            
    if message.content.startswith("!link"):
            try:
                voice_client = await message.author.voice.channel.connect()
                voice_clients[voice_client.guild.id] = voice_client
            except Exception as e:
                print(e)

            try:
                url = message.content.split()[1]

                loop = asyncio.get_event_loop()
                data = await loop.run_in_executor(None, lambda: ytdl.extract_info(url, download=False))

                song = data['url']
                player = discord.FFmpegOpusAudio(song, **ffmpeg_options)

                voice_clients[message.guild.id].play(player)
            except Exception as e:
                print(e)

    # Xử lý lệnh !queue
    elif message.content.startswith("!queue"):
        queue = queues.get(guild_id, [])
        if queue:
            await message.channel.send("Danh sách chờ:")
            for index, item in enumerate(queue, 1):
                await message.channel.send(f"{index}. {item.title}")
        else:
            await message.channel.send("Không có bài hát nào trong danh sách chờ.")

    # Xử lý lệnh !skip
    elif message.content.startswith("!skip"):
        try:
            if voice_client and voice_client.is_playing():
                voice_client.stop()
                await play_next_song(guild_id, queues, voice_client, skip=True)
                await remove_first_line_from_log()
        except Exception as e:
            print(e)

    # Xử lý các lệnh như !pause, !resume, !stop
    elif message.content.startswith("!pause"):
        try:
            if voice_client and voice_client.is_playing():
                voice_client.pause()
        except Exception as e:
            print(e)

    elif message.content.startswith("!resume"):
        try:
            if voice_client and not voice_client.is_playing():
                voice_client.resume()
        except Exception as e:
            print(e)

    elif message.content.startswith("!stop"):
        try:
            if voice_client:
                voice_client.stop()
                await voice_client.disconnect()
                del voice_clients[guild_id]  # Xóa voice_client sau khi dừng
        except Exception as e:
            print(e)

async def log_song_title(title):
    log_file_path = "C:\\Bot Music 2\\song_log.txt"
    try:
        # Kiểm tra xem tệp tin log đã tồn tại chưa
        if not os.path.exists(log_file_path):
            # Nếu chưa tồn tại, tạo tệp tin mới và ghi title vào tệp tin đó
            with open(log_file_path, 'w', encoding='utf-8') as file:
                file.write(title + '\n')
        else:
            # Nếu tệp tin log đã tồn tại, mở tệp tin và chèn title vào cuối tệp tin
            with open(log_file_path, 'a', encoding='utf-8') as file:
                file.write(title + '\n')
    except Exception as e:
        print(f"Error logging song title: {e}")

async def remove_first_line_from_log():
    log_file_path = "C:\\Bot Music 2\\song_log.txt"
    try:
        with open(log_file_path, "r", encoding="utf-8") as f:
            lines = f.readlines()
        # Xóa dòng đầu tiên trong list lines
        lines = lines[1:]
        with open(log_file_path, "w", encoding="utf-8") as f:
            for line in lines:
                f.write(line)
    except Exception as e:
        print(f"Error removing first line from log: {e}")
        
async def clear_log_file():
    log_file_path = "C:\\Bot Music 2\\song_log.txt"
    try:
        with open(log_file_path, "w", encoding="utf-8") as f:
            f.truncate(0)
    except Exception as e:
        print(f"Error clearing log file: {e}")


async def play_next_song(guild_id, queues, voice_client, skip=False):
    queue = queues.get(guild_id, [])
    if queue:
        player = queue.pop(0)
        voice_client.play(player, after=lambda e: asyncio.run_coroutine_threadsafe(play_next_song(guild_id, queues, voice_client, skip=False), voice_client.loop))
        if skip:
            return
        else:
            await remove_first_line_from_log()  # Xóa dòng đầu tiên trong file log
    elif skip:
        await remove_first_line_from_log()  # Xóa dòng đầu tiên trong file log
        await voice_client.disconnect()
        del voice_client[guild_id]  # Xóa voice_client sau khi dừng
    else:
        await clear_log_file()  # Xóa dòng đầu tiên trong file log
        await voice_client.disconnect()
        del voice_client[guild_id]  # Xóa voice_client sau khi dừng


    


    I have tried asking ChatGPT, Gemini, or Bing, and they always lead me into a loop of errors that cannot be resolved. This error only occurs when the song naturally finishes playing due to its duration. If the song is playing and I use the command !skip, the next song in the queue will play and function normally. I noticed that it seems like if a song ends naturally, the song queue is also cleared immediately. I hope someone can help me with this

    


  • Trying to encode video file as hevc error in python

    29 juin 2022, par jatt

    I am getting a syntax error when trying to run this code with it saying the end quotes being the error. process = sp.Popen(shlex.split(f'usr/bin/ffmpeg -y -s {width}x{height} -pixel_format bgr24 -f rawvideo -r {fps} -i pipe: -vcodec libx265 -pix_fmt yuv420p -crf 24 {output_filename}') stdin=sp.PIPE)

    


    I don't know why because the end quote is supposed to be there and I am not sure how to fix it.
The original code is from here : How to output x265 compressed video with cv2.VideoWriter

    


    import cv2
import numpy as np
import subprocess as sp
import shlex

width, height, n_frames, fps = 1344, 756, 50, 25  # 50 frames, resolution 1344x756, and 25 fps

output_filename = 'output.mp4'

# Open ffmpeg application as sub-process
# FFmpeg input PIPE: RAW images in BGR color format
# FFmpeg output MP4 file encoded with HEVC codec.
# Arguments list:
# -y                   Overwrite output file without asking
# -s {width}x{height}  Input resolution width x height (1344x756)
# -pixel_format bgr24  Input frame color format is BGR with 8 bits per color component
# -f rawvideo          Input format: raw video
# -r {fps}             Frame rate: fps (25fps)
# -i pipe:             ffmpeg input is a PIPE
# -vcodec libx265      Video codec: H.265 (HEVC)
# -pix_fmt yuv420p     Output video color space YUV420 (saving space compared to YUV444)
# -crf 24              Constant quality encoding (lower value for higher quality and larger output file).
# {output_filename}    Output file name: output_filename (output.mp4)
process = sp.Popen(shlex.split(f'usr/bin/ffmpeg -y -s {width}x{height} -pixel_format bgr24 -f rawvideo -r {fps} -i pipe: -vcodec libx265 -pix_fmt yuv420p -crf 24 {output_filename}') stdin=sp.PIPE)

# Build synthetic video frames and write them to ffmpeg input stream.
for i in range(n_frames):
    # Build synthetic image for testing ("render" a video frame).
    img = np.full((height, width, 3), 60, np.uint8)
    cv2.putText(img, str(i+1), (width//2-100*len(str(i+1)), height//2+100), cv2.FONT_HERSHEY_DUPLEX, 10, (255, 30, 30), 20)  # Blue number

    # Write raw video frame to input stream of ffmpeg sub-process.
    process.stdin.write(img.tobytes())

# Close and flush stdin
process.stdin.close()

# Wait for sub-process to finish
process.wait()

# Terminate the sub-process
process.terminate()


    


  • How to add "ffmpeg" to the Cloud Run environment or to Dockerfile ?

    16 janvier 2021, par awabs

    I am triying to a logo to video that is uploaded to cloud storage using ffmpeg library, I deployed this code as cloud function is runs only with small size videos, so I decided to move to cloud run, but here I have to build container myself so I used this command instead

    


    gcloud builds submit --pack image=europe-west1-docker.pkg.dev/video-sharing-a1mfa/video-sharing-repo/my-image,env=GOOGLE_FUNCTION_TARGET=addLogo


    


    and it builds the image and I just had to create a service in the Cloud Run and it is running, but unfortunately when I trigger this function I get this error

    


    Error: spawn ffmpeg ENOENT
at Process.ChildProcess._handle.onexit (internal/child_process.js:268:19)
at onErrorNT (internal/child_process.js:470:16)
at processTicksAndRejections (internal/process/task_queues.js:84:21)


    


    Which I am not sure of but I guess is that ffmpeg in not installed in contanier (where it comes preinstalled in the gcloud functions env). Any idea how to install it or what the docker file configuration might be ?

    


    here is my code :

    


    const { Storage } = require('@google-cloud/storage');
const projectId = 'video-sharing-a1mfa';
let gcs = new Storage({
    projectId
});

const os = require('os');
const path = require('path');
const spawn = require('child-process-promise').spawn;


exports.addLogo = async (req, res) => {

const event = JSON.parse(req.body);
const bucket = event.bucket;
const contentType = event.contentType;
const filePath = event.name;

console.log('File change detected, function execution started');
if (path.basename(filePath).startsWith('resized-')) {
    console.log('We already renamed that file!');
    return;
}
const destBucket = gcs.bucket(bucket);
const tmpFilePath = path.join(os.tmpdir(), path.basename(filePath));
const metadata = { contentType: contentType };
const tmpLogoPath = path.join(os.tmpdir(), 'watermark.png');
await destBucket.file('watermark.png').download({
    destination: tmpLogoPath
})

const newPath = path.join(os.tmpdir(), 'output.mp4')

await destBucket.file(filePath).download({
    destination: tmpFilePath
});
console.log('file downloaded to temp');

console.log('adding watermark');

var str = "overlay=10:10"

await spawn('ffmpeg', ['-i', tmpFilePath, '-i', tmpLogoPath, '-filter_complex', str, newPath]);


console.log('watermark added');

return destBucket.upload(newPath, {
    destination: path.dirname(filePath) + '/resized-' + path.basename(filePath),
    metadata: metadata
});;
};