如何将 ogg 文件转换为电报语音格式?

how convert ogg file to telegram voice format?

我正在尝试通过电报机器人中的 SendVoice 方法发送语音消息,但它会将语音作为文档文件发送(未播放)。

ogg 文件由 ffmpeg 转换为 opus 编码。

https://api.telegram.org/bot<token>/sendVoice?chat_id=x&voice=http://music-farsi.ir/ogg/voice.ogg

my ogg 文件和 telegram 语音消息有什么区别?

我的 ogg 文件:ogg file

sendVoice 方法的 MIME 类型必须设置为 audio/ogg。您的示例设置为 video/ogg.

可以找到有关带有 url 的 sendVoice 方法的更多信息 here

如果你想让它显示音频频谱图,确保 ogg 是用 opus 编解码器编码的

多亏了 YoilyL,我才能够使用频谱图发送语音消息。

这是我的 python 脚本,它将我的 .wav 文件转换为 .ogg:

import os
import requests
import subprocess

token = YYYYYYY
chat_id = XXXXXXXX

upload_audio_url = "https://api.telegram.org/bot%s/sendAudio?chat_id=%s" % (token, chat_id)
audio_path_wav = '/Users/me/some-file.wav'

# Convert the file from wav to ogg
filename = os.path.splitext(audio_path_wav)[0]
audio_path_ogg = filename + '.ogg'
subprocess.run(["ffmpeg", '-i', audio_path_wav, '-acodec', 'libopus', audio_path_ogg, '-y'])

with open(audio_path_ogg, 'rb') as f:
    data = f.read()

# An arbitrary .ogg filename has to be present so that the spectogram is shown
file = {'audio': ('Message.ogg', data)}
result = requests.post(upload_audio_url, files=file)

这导致语音消息呈现如下:

您需要使用您选择的包管理器安装 ffmpeg

Telegram 有两个 API 用于发送音频文件:sendVoicesendAudio

要获得频谱图,您需要使用 sendVoice API。

Use this method to send audio files, if you want Telegram clients to display the file as a playable voice message. For this to work, your audio must be in an .OGG file encoded with OPUS (other formats may be sent as Audio or Document). On success, the sent Message is returned. Bots can currently send voice messages of up to 50 MB in size, this limit may be changed in the future.

此外,请注意 docs 中提到的其他限制:

To use sendVoice, the file must have the type audio/ogg and be no more than 1MB in size. 1-20MB voice notes will be sent as files.

因此,如果您发送小于 1MB 的 opus 格式的 ogg 文件,您将获得频谱图。如果 ogg 文件大于 1MB,它仍将作为语音上传,但没有频谱条。

您可以在 linux 中使用低比特率的 ffmpeg 来减小文件的大小:

ffmpeg -i input.mp3 -vn -acodec libopus -b:a 16k audio.ogg

这是一个示例 python 代码,用于使用 sendVoice

将示例 ogg 文件发送到频道
import os, sys
import requests

# Bot token
token = ''

if len(sys.argv) <=1:
    print("Usage: send_voice.py destchannelid filename")
    print("\te.g.")
    print("\tsend_voice.py -10011111111 audio.ogg")
    print("Convert audio files to ogg using the following command")
    print("ffmpeg -i input.mp3 -vn -acodec libopus -b:a 16k audio.ogg")
    exit()

upload_audio_url = "https://api.telegram.org/bot{}/sendVoice?chat_id={}".format(token,chat_id)
audio_path_ogg = os.getcwd() + "/" + sys.argv[2]

with open(audio_path_ogg, 'rb') as f:
    data = f.read()

file = {'voice': ('Message.ogg', data)}
result = requests.post(upload_audio_url, files=file)
print(result.content)