
Recherche avancée
Autres articles (64)
-
Contribute to a better visual interface
13 avril 2011MediaSPIP is based on a system of themes and templates. Templates define the placement of information on the page, and can be adapted to a wide range of uses. Themes define the overall graphic appearance of the site.
Anyone can submit a new graphic theme or template and make it available to the MediaSPIP community. -
Qualité du média après traitement
21 juin 2013, parLe bon réglage du logiciel qui traite les média est important pour un équilibre entre les partis ( bande passante de l’hébergeur, qualité du média pour le rédacteur et le visiteur, accessibilité pour le visiteur ). Comment régler la qualité de son média ?
Plus la qualité du média est importante, plus la bande passante sera utilisée. Le visiteur avec une connexion internet à petit débit devra attendre plus longtemps. Inversement plus, la qualité du média est pauvre et donc le média devient dégradé voire (...) -
Qu’est ce qu’un éditorial
21 juin 2013, parEcrivez votre de point de vue dans un article. Celui-ci sera rangé dans une rubrique prévue à cet effet.
Un éditorial est un article de type texte uniquement. Il a pour objectif de ranger les points de vue dans une rubrique dédiée. Un seul éditorial est placé à la une en page d’accueil. Pour consulter les précédents, consultez la rubrique dédiée.
Vous pouvez personnaliser le formulaire de création d’un éditorial.
Formulaire de création d’un éditorial Dans le cas d’un document de type éditorial, les (...)
Sur d’autres sites (8886)
-
How to get the first audio channel from a video with ffmpeg-python ?
31 mai 2022, par giskI would like to get the very first audio channel from a video using ffmpeg-python.


I tried with this :


out, _ = (
 ffmpeg
 .input(filename)
 .output('pipe:', loglevel=0, format='s16le', acodec='pcm_s16le', ac=1, ar='8k')
 .run(capture_stdout=True)
 )
 """ extract audio signal """
 self.signal = (
 np
 .frombuffer(out, np.int16) 
 )



but I am not sure whether this is correct.


I had a look here, but I could not find a solution : https://trac.ffmpeg.org/wiki/AudioChannelManipulation


Any suggestion ? Thanks !


EDIT :


I tried @rotem solution and it seems to work. However, I have another issue which seems related to the -ac flag. For some videos, the numpy output has the right length (i.e., it matches the original audio length). For others, I get a wrong one. However, if I set -ac to 2 for these videos, I get the correct signal length. Do you know why is this happening ?


This is the metadata of the video (duration : 2 minutes and 11 seconds) which outputs the correct numpy array size with setting -ac to 2


'streams' : ['index' : 0, 'codec_name' : 'h264', 'codec_long_name' : 'H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10', 'profile' : 'High', 'codec_type' : 'video', 'codec_tag_string' : 'avc1', 'codec_tag' : '0x31637661', 'width' : 1920, 'height' : 1080, 'coded_width' : 1920, 'coded_height' : 1080, 'closed_captions' : 0, 'film_grain' : 0, 'has_b_frames' : 0, 'pix_fmt' : 'yuv420p', 'level' : 40, 'color_range' : 'tv', 'color_space' : 'bt709', 'color_transfer' : 'bt709', 'color_primaries' : 'bt709', 'chroma_location' : 'left', 'field_order' : 'progressive', 'refs' : 1, 'is_avc' : 'true', 'nal_length_size' : '4', 'id' : '0x1', 'r_frame_rate' : '30/1', 'avg_frame_rate' : '176805000/5894849', 'time_base' : '1/90000', 'start_pts' : 0, 'start_time' : '0.000000', 'duration_ts' : 11789698, 'duration' : '130.996644', 'bit_rate' : '16999840', 'bits_per_raw_sample' : '8', 'nb_frames' : '3929', 'extradata_size' : 34, 'disposition' : 'default' : 1, 'dub' : 0, 'original' : 0, 'comment' : 0, 'lyrics' : 0, 'karaoke' : 0, 'forced' : 0, 'hearing_impaired' : 0, 'visual_impaired' : 0, 'clean_effects' : 0, 'attached_pic' : 0, 'timed_thumbnails' : 0, 'captions' : 0, 'descriptions' : 0, 'metadata' : 0, 'dependent' : 0, 'still_image' : 0, 'tags' : 'creation_time' : '2022-05-30T15:00:39.000000Z', 'language' : 'eng', 'handler_name' : 'VideoHandle', 'vendor_id' : '[0][0][0][0]', 'index' : 1, 'codec_name' : 'aac', 'codec_long_name' : 'AAC (Advanced Audio Coding)', 'profile' : 'LC', 'codec_type' : 'audio', 'codec_tag_string' : 'mp4a', 'codec_tag' : '0x6134706d', 'sample_fmt' : 'fltp', 'sample_rate' : '48000', 'channels' : 2, 'channel_layout' : 'stereo', 'bits_per_sample' : 0, 'id' : '0x2', 'r_frame_rate' : '0/0', 'avg_frame_rate' : '0/0', 'time_base' : '1/48000', 'start_pts' : 696, 'start_time' : '0.014500', 'duration_ts' : 6285214, 'duration' : '130.941958', 'bit_rate' : '256004', 'nb_frames' : '6138', 'extradata_size' : 2, 'disposition' : 'default' : 1, 'dub' : 0, 'original' : 0, 'comment' : 0, 'lyrics' : 0, 'karaoke' : 0, 'forced' : 0, 'hearing_impaired' : 0, 'visual_impaired' : 0, 'clean_effects' : 0, 'attached_pic' : 0, 'timed_thumbnails' : 0, 'captions' : 0, 'descriptions' : 0, 'metadata' : 0, 'dependent' : 0, 'still_image' : 0, 'tags' : 'creation_time' : '2022-05-30T15:00:39.000000Z', 'language' : 'eng', 'handler_name' : 'SoundHandle', 'vendor_id' : '[0][0][0][0]'], 'format' : 'filename' : 'videos4/test_01.mp4', 'nb_streams' : 2, 'nb_programs' : 0, 'format_name' : 'mov,mp4,m4a,3gp,3g2,mj2', 'format_long_name' : 'QuickTime / MOV', 'start_time' : '0.000000', 'duration' : '130.996600', 'size' : '282621379', 'bit_rate' : '17259768', 'probe_score' : 100, 'tags' : 'major_brand' : 'mp42', 'minor_version' : '0', 'compatible_brands' : 'isommp42', 'creation_time' : '2022-05-30T15:00:39.000000Z', 'com.android.version' : '12', 'com.android.capture.fps' : '30.000000'.


This is instead, the metadata of the video (duration 5 minutes) which gives the right result length with setting -ac to 1 :


'streams' : ['index' : 0, 'codec_name' : 'h264', 'codec_long_name' : 'H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10', 'profile' : 'High', 'codec_type' : 'video', 'codec_tag_string' : 'avc1', 'codec_tag' : '0x31637661', 'width' : 1920, 'height' : 1080, 'coded_width' : 1920, 'coded_height' : 1080, 'closed_captions' : 0, 'film_grain' : 0, 'has_b_frames' : 0, 'sample_aspect_ratio' : '1:1', 'display_aspect_ratio' : '16:9', 'pix_fmt' : 'yuv420p', 'level' : 40, 'field_order' : 'progressive', 'refs' : 1, 'is_avc' : 'true', 'nal_length_size' : '4', 'id' : '0x1', 'r_frame_rate' : '30/1', 'avg_frame_rate' : '33862500/1128779', 'time_base' : '1/90000', 'start_pts' : 0, 'start_time' : '0.000000', 'duration_ts' : 27090696, 'duration' : '301.007733', 'bit_rate' : '16999542', 'bits_per_raw_sample' : '8', 'nb_frames' : '9030', 'extradata_size' : 26, 'disposition' : 'default' : 1, 'dub' : 0, 'original' : 0, 'comment' : 0, 'lyrics' : 0, 'karaoke' : 0, 'forced' : 0, 'hearing_impaired' : 0, 'visual_impaired' : 0, 'clean_effects' : 0, 'attached_pic' : 0, 'timed_thumbnails' : 0, 'captions' : 0, 'descriptions' : 0, 'metadata' : 0, 'dependent' : 0, 'still_image' : 0, 'tags' : 'language' : 'und', 'handler_name' : 'VideoHandler', 'vendor_id' : '[0][0][0][0]', 'side_data_list' : ['side_data_type' : 'Display Matrix', 'displaymatrix' : '\n00000000 : 0 65536 0\n00000001 : -65536 0 0\n00000002 : 0 0 1073741824\n', 'rotation' : -90], 'index' : 1, 'codec_name' : 'aac', 'codec_long_name' : 'AAC (Advanced Audio Coding)', 'profile' : 'LC', 'codec_type' : 'audio', 'codec_tag_string' : 'mp4a', 'codec_tag' : '0x6134706d', 'sample_fmt' : 'fltp', 'sample_rate' : '48000', 'channels' : 2, 'channel_layout' : 'stereo', 'bits_per_sample' : 0, 'id' : '0x2', 'r_frame_rate' : '0/0', 'avg_frame_rate' : '0/0', 'time_base' : '1/48000', 'start_pts' : 0, 'start_time' : '0.000000', 'duration_ts' : 14448640, 'duration' : '301.013333', 'bit_rate' : '256000', 'nb_frames' : '14110', 'extradata_size' : 2, 'disposition' : 'default' : 1, 'dub' : 0, 'original' : 0, 'comment' : 0, 'lyrics' : 0, 'karaoke' : 0, 'forced' : 0, 'hearing_impaired' : 0, 'visual_impaired' : 0, 'clean_effects' : 0, 'attached_pic' : 0, 'timed_thumbnails' : 0, 'captions' : 0, 'descriptions' : 0, 'metadata' : 0, 'dependent' : 0, 'still_image' : 0, 'tags' : 'language' : 'und', 'handler_name' : 'SoundHandler', 'vendor_id' : '[0][0][0][0]'], 'format' : 'filename' : 'videos4/video_02.mp4', 'nb_streams' : 2, 'nb_programs' : 0, 'format_name' : 'mov,mp4,m4a,3gp,3g2,mj2', 'format_long_name' : 'QuickTime / MOV', 'start_time' : '0.000000', 'duration' : '301.014000', 'size' : '649577064', 'bit_rate' : '17263703', 'probe_score' : 100, 'tags' : 'major_brand' : 'isom', 'minor_version' : '512', 'compatible_brands' : 'isomiso2avc1mp41', 'encoder' : 'Lavf58.27.103'


-
Discord.py repository example : bot can join voice channel, shows voice activity (green ring), but no sound is produced ?
19 juin 2023, par Jared RobertsonI 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 :


- 

-
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.


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


-
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).


-
All libraries up to date.


-
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.


-
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


-
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.


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




















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.


-
-
Discord bot leaving voice channel immediatly after joining
24 juillet 2017, par ForbI am building a bot for my discord server to play the audio YouTube videos as I haven’t found a reliable bot online.
The bot connects to my voice channel after I type the !play url command but immediately leaves even if the URL is valid.
My code is below :
[Command("play", RunMode = RunMode.Async)]
public async Task play(string url) {
IVoiceChannel channel = (Context.User as IVoiceState).VoiceChannel;
IAudioClient client = await channel.ConnectAsync();
var output = CreateStream(url).StandardOutput.BaseStream;
var stream = client.CreatePCMStream(AudioApplication.Music, 128 * 1024);
output.CopyToAsync(stream);
stream.FlushAsync().ConfigureAwait(false);
}
private Process CreateStream(string url) {
Process currentsong = new Process();
currentsong.StartInfo = new ProcessStartInfo {
FileName = "cmd.exe",
Arguments = $"/C youtube-dl -o - {url} | ffmpeg -i pipe:0 -ac 2 -f s16le -ar 48000 pipe:1",
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = true
};
currentsong.Start();
return currentsong;
}I have tried using just ffmpeg with a file on my PC which was hard coded in, but I had the same result and the bot left the voice channel as soon as it connected.
I did verify that both ffmpeg and youtube-dl were working by running the commands in a cmd window and they both ran fine.