Recherche avancée

Médias (3)

Mot : - Tags -/collection

Autres articles (74)

  • La sauvegarde automatique de canaux SPIP

    1er avril 2010, par

    Dans le cadre de la mise en place d’une plateforme ouverte, il est important pour les hébergeurs de pouvoir disposer de sauvegardes assez régulières pour parer à tout problème éventuel.
    Pour réaliser cette tâche on se base sur deux plugins SPIP : Saveauto qui permet une sauvegarde régulière de la base de donnée sous la forme d’un dump mysql (utilisable dans phpmyadmin) mes_fichiers_2 qui permet de réaliser une archive au format zip des données importantes du site (les documents, les éléments (...)

  • Amélioration de la version de base

    13 septembre 2013

    Jolie sélection multiple
    Le plugin Chosen permet d’améliorer l’ergonomie des champs de sélection multiple. Voir les deux images suivantes pour comparer.
    Il suffit pour cela d’activer le plugin Chosen (Configuration générale du site > Gestion des plugins), puis de configurer le plugin (Les squelettes > Chosen) en activant l’utilisation de Chosen dans le site public et en spécifiant les éléments de formulaires à améliorer, par exemple select[multiple] pour les listes à sélection multiple (...)

  • Emballe médias : à quoi cela sert ?

    4 février 2011, par

    Ce plugin vise à gérer des sites de mise en ligne de documents de tous types.
    Il crée des "médias", à savoir : un "média" est un article au sens SPIP créé automatiquement lors du téléversement d’un document qu’il soit audio, vidéo, image ou textuel ; un seul document ne peut être lié à un article dit "média" ;

Sur d’autres sites (7424)

  • Révision 18479 : Aider à résoudre #2247 :

    9 septembre 2011, par cedric -

    eviter de creer une ré-entrance inutilie dans lister_tables_objets_sql. Pour ce faire on déplace les deux fonctions declarer_tables_principales et declarer_tables_auxiliaires dans base/objets, et les deux fichiers inc/serial et inc/auxiliaires ne sont plus là que pour compatibilité (puisqu’on (...)

  • Can't view and record graph at the same time using FFMpegWriter [closed]

    7 juillet 2024, par Barkın Özer

    So this code is used for graphing and logging sensor data coming from bluetooth ports. I wanted to add an function that will record the graph in mp4 format. In order to achieve this I used ffmpegWriter. The issue is while this code records the graph I can't view the graph at the same time.

    


    import serial
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation, FFMpegWriter
import openpyxl
from datetime import datetime

# Constants
GRAVITY = 9.81  # Standard gravity in m/s²

# Initialize serial connections to HC-06 devices
ser_x_accel = serial.Serial('COM4', 9600, timeout=1)  # X-axis acceleration data
ser_y_angle = serial.Serial('COM11', 9600, timeout=1)  # Y-axis angle data

# Initialize empty lists to store data
x_accel_data = []
y_angle_data = []
timestamps = []

# Initialize Excel workbook
wb = openpyxl.Workbook()
ws = wb.active
ws.title = "Sensor Data"
ws.append(["Timestamp", "X Acceleration (m/s²)", "Y Angle (degrees)"])

# Function to update the plot and log data
def update(frame):
    # Read data from serial connections
    line_x_accel = ser_x_accel.readline().decode('utf-8').strip()
    line_y_angle = ser_y_angle.readline().decode('utf-8').strip()
    
    try:
        # Parse and process X-axis acceleration data
        x_accel_g = float(line_x_accel)  # Acceleration in g read from serial
        x_accel_ms2 = x_accel_g * GRAVITY  # Convert from g to m/s²
        x_accel_data.append(x_accel_ms2)
        
        # Parse and process Y-axis angle data
        y_angle = float(line_y_angle)
        y_angle_data.append(y_angle)
        
        # Append timestamp
        timestamps.append(datetime.now())

        # Limit data points to show only the latest 100
        if len(x_accel_data) > 100:
            x_accel_data.pop(0)
            y_angle_data.pop(0)
            timestamps.pop(0)

        # Log data to Excel with timestamp
        timestamp_str = timestamps[-1].strftime("%H:%M:%S")
        ws.append([timestamp_str, x_accel_data[-1], y_angle_data[-1]])

        # Clear and update plots
        ax1.clear()
        ax1.plot(timestamps, x_accel_data, label='X Acceleration', color='b')
        ax1.legend(loc='upper left')
        ax1.set_ylim([-20, 20])  # Adjust based on expected acceleration range in m/s²
        ax1.set_title('Real-time X Acceleration Data')
        ax1.set_xlabel('Time')
        ax1.set_ylabel('Acceleration (m/s²)')
        ax1.grid(True)

        ax2.clear()
        ax2.plot(timestamps, y_angle_data, label='Y Angle', color='g')
        ax2.legend(loc='upper left')
        ax2.set_ylim([-180, 180])
        ax2.set_title('Real-time Y Angle Data')
        ax2.set_xlabel('Time')
        ax2.set_ylabel('Angle (degrees)')
        ax2.grid(True)

        # Update text boxes with latest values
        text_box.set_text(f'X Acceleration: {x_accel_data[-1]:.2f} m/s²')
        text_box2.set_text(f'Y Angle: {y_angle_data[-1]:.2f}°')
        
        # Save the workbook periodically (every 100 updates)
        if frame % 100 == 0:
            wb.save("sensor_data.xlsx")
        
    except ValueError:
        pass  # Ignore lines that are not properly formatted

# Setup the plots
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(10, 8))
text_box = ax1.text(0.05, 0.95, '', transform=ax1.transAxes, fontsize=12, verticalalignment='top', bbox=dict(boxstyle='round', facecolor='wheat', alpha=0.5))
text_box2 = ax2.text(0.05, 0.95, '', transform=ax2.transAxes, fontsize=12, verticalalignment='top', bbox=dict(boxstyle='round', facecolor='wheat', alpha=0.5))

# Animate the plots
ani = FuncAnimation(fig, update, interval=100)  # Update interval of 100ms

# Save the animation as a video file
writer = FFMpegWriter(fps=10, metadata=dict(artist='Me'), bitrate=1800)
ani.save("sensor_data.mp4", writer=writer)

plt.tight_layout()
plt.show()

# Save the workbook at the end of the session
wb.save("sensor_data.xlsx")



    


    I tried using OpenCV to record the graph but then I didn't even got any recording. I think solving this issue with my original code would be a better approach.

    


  • Discord.py repository example : bot can join voice channel, shows voice activity (green ring), but no sound is produced ?

    19 juin 2023, par Jared Robertson

    I copied an example from the discord.py repository to test out a bot with music capabilities. Though the code enables YouTube playback, I am only concerned with local audio playback. See code here : https://github.com/Rapptz/discord.py/blob/v2.3.0/examples/basic_voice.py. I tested this code as is with only the Discord token portion updated (from constants.py). See code below :

    


    # This example requires the 'message_content' privileged intent to function.

#my constants.py with API keys, tokens, etc. stored
import constants

import asyncio

import discord
import youtube_dl

from discord.ext import commands

# Suppress noise about console usage from errors
youtube_dl.utils.bug_reports_message = lambda: ''


ytdl_format_options = {
    'format': 'bestaudio/best',
    'outtmpl': '%(extractor)s-%(id)s-%(title)s.%(ext)s',
    'restrictfilenames': True,
    'noplaylist': True,
    'nocheckcertificate': True,
    'ignoreerrors': False,
    'logtostderr': False,
    'quiet': True,
    'no_warnings': True,
    'default_search': 'auto',
    'source_address': '0.0.0.0',  # bind to ipv4 since ipv6 addresses cause issues sometimes
}

ffmpeg_options = {
    'options': '-vn',
}

ytdl = youtube_dl.YoutubeDL(ytdl_format_options)


class YTDLSource(discord.PCMVolumeTransformer):
    def __init__(self, source, *, data, volume=0.5):
        super().__init__(source, volume)

        self.data = data

        self.title = data.get('title')
        self.url = data.get('url')

    @classmethod
    async def from_url(cls, url, *, loop=None, stream=False):
        loop = loop or asyncio.get_event_loop()
        data = await loop.run_in_executor(None, lambda: ytdl.extract_info(url, download=not stream))

        if 'entries' in data:
            # take first item from a playlist
            data = data['entries'][0]

        filename = data['url'] if stream else ytdl.prepare_filename(data)
        return cls(discord.FFmpegPCMAudio(filename, **ffmpeg_options), data=data)


class Music(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.command()
    async def join(self, ctx, *, channel: discord.VoiceChannel):
        """Joins a voice channel"""

        if ctx.voice_client is not None:
            return await ctx.voice_client.move_to(channel)

        await channel.connect()

    @commands.command()
    async def play(self, ctx, *, query):
        """Plays a file from the local filesystem"""

        source = discord.PCMVolumeTransformer(discord.FFmpegPCMAudio(query))
        ctx.voice_client.play(source, after=lambda e: print(f'Player error: {e}') if e else None)

        await ctx.send(f'Now playing: {query}')

    @commands.command()
    async def yt(self, ctx, *, url):
        """Plays from a url (almost anything youtube_dl supports)"""

        async with ctx.typing():
            player = await YTDLSource.from_url(url, loop=self.bot.loop)
            ctx.voice_client.play(player, after=lambda e: print(f'Player error: {e}') if e else None)

        await ctx.send(f'Now playing: {player.title}')

    @commands.command()
    async def stream(self, ctx, *, url):
        """Streams from a url (same as yt, but doesn't predownload)"""

        async with ctx.typing():
            player = await YTDLSource.from_url(url, loop=self.bot.loop, stream=True)
            ctx.voice_client.play(player, after=lambda e: print(f'Player error: {e}') if e else None)

        await ctx.send(f'Now playing: {player.title}')

    @commands.command()
    async def volume(self, ctx, volume: int):
        """Changes the player's volume"""

        if ctx.voice_client is None:
            return await ctx.send("Not connected to a voice channel.")

        ctx.voice_client.source.volume = volume / 100
        await ctx.send(f"Changed volume to {volume}%")

    @commands.command()
    async def stop(self, ctx):
        """Stops and disconnects the bot from voice"""

        await ctx.voice_client.disconnect()

    @play.before_invoke
    @yt.before_invoke
    @stream.before_invoke
    async def ensure_voice(self, ctx):
        if ctx.voice_client is None:
            if ctx.author.voice:
                await ctx.author.voice.channel.connect()
            else:
                await ctx.send("You are not connected to a voice channel.")
                raise commands.CommandError("Author not connected to a voice channel.")
        elif ctx.voice_client.is_playing():
            ctx.voice_client.stop()


intents = discord.Intents.default()
intents.message_content = True

bot = commands.Bot(
    command_prefix=commands.when_mentioned_or("!"),
    description='Relatively simple music bot example',
    intents=intents,
)


@bot.event
async def on_ready():
    print(f'Logged in as {bot.user} (ID: {bot.user.id})')
    print('------')


async def main():
    async with bot:
        await bot.add_cog(Music(bot))
        #referenced my discord token in constants.py
        await bot.start(constants.discord_token)


asyncio.run(main())


    


    This code should cause the Discord bot to join the voice channel and play a local audio file when the message " !play query" is entered into the Discord text channel, with query in my case being "test.mp3." When " !play test.mp3" is entered, the bot does join the voice channel and appears to generate voice activity, however no sound is heard. No errors are thrown in the output. The bot simply continues on silently.

    


    Here's what I've checked and tried :

    


      

    1. I am in the Discord voice channel. The code will alert that user is not in the voice channel if a user attempts to summon the bot without being in a voice channel.

      


    2. 


    3. FFmpeg is installed and added to PATH. I even stored a copy of the .exe in the project folder.

      


    4. 


    5. I've tried specifying the full path of both FFmpeg (adding the "executable=" arg to the play function) and the audio file (stored at C :/test.mp3 and a copy in the project folder).

      


    6. 


    7. All libraries up to date.

      


    8. 


    9. Reviewed discord.py docs (https://discordpy.readthedocs.io/en/stable/api.html#voice-related) and played around with opuslib (docs say not necessary on Windows, which I'm on) and FFmpegOpusAudio, but results were the same.

      


    10. 


    11. Referenced numerous StackOverflow threads, including every one suggested when I typed the title of this post. Tried each suggestion individually and in various combinations when possible. See a few below :
Discord.py music_cog, bot joins channel but plays no sound
Discord.py Music Bot doesn’t play music
Discord.py Bot Not Playing music

      


    12. 


    13. Double checked my sound is on and volume turned up. My sound is working I can hear the Discord notification when the bot joins the voice channel.

      


    14. 


    15. Issue is the same if I try to play a YouTube file with !yt command. Bot joins channel fine but no sound is produced.

      


    16. 


    


    That's everything I can think of at the moment. There seem to be many posts regarding this exact topic and also variations of it. I've been unable to find a clear and consistent answer, nor one the works for me. I am willing to try anything at this point as it is obviously possible, but for whatever reason success eludes me. Thank you in advance for any assistance you are willing to offer.