在Firebase上使用Python为视频添加音频。

huangapple go评论58阅读模式
英文:

add an audio to a video on Firebase using python

问题

Firebase似乎让编辑视频变得非常困难,它在模拟器中可以工作,但在部署或反之时则无法。我一直试图通过一个函数简单地将音频文件添加到视频中。目前输出存在,但文件大小为0字节。

这是我用于这个特定示例的测试函数:

它会给你一个链接,假设你在testfiles文件夹中有video.mp4和audio.mp3文件,它会将它们上传到输入存储桶,然后到触发存储桶以运行函数来添加这两个文件并将它们输出到输出存储桶。但ffmpeg并不总是有效,moviepy也不总是有效,而且速度太慢。

@https_fn.on_request(region="europe-west2", memory=1024)
def addTestBuckets2(req: https_fn.Request) -> https_fn.Response:

    # 创建存储桶
    testBucketInput = storage.bucket("testbucketinput")
    testBucketOutput = storage.bucket("testbucketoutput")
    testBucketTrigger = storage.bucket("testbuckettrigger")

    # 上传测试文件
    testBucketInput.blob("audio.mp3").upload_from_filename(
        "D:/backendfunctions/functions/testfiles/audio.mp3")
    testBucketInput.blob("video.mp4").upload_from_filename(
        "D:/backendfunctions/functions/testfiles/video.mp4")

    open("trigger.txt", "w").close()
    testBucketTrigger.blob("trigger.txt").upload_from_filename(
        "trigger.txt")

    # 尝试从存储桶中循环下载output.mp4文件
    keepTrying = 0
    while keepTrying < 100:
        try:
            testBucketOutput.blob("output.mp4").download_to_filename(
                "output.mp4")
            break
        except:
            sleep(.1)
            keepTrying += 1

    # os.remove("output.mp4")

    # 返回响应
    return https_fn.Response("Bucket tested")


@storage_fn.on_object_finalized(bucket="testbuckettrigger", region=region)
def editvidtestfunction(event: storage_fn.CloudEvent[storage_fn.StorageObjectData | None],) -> None:
    """测试编辑函数的限制"""

    # 从事件中获取文件路径
    file_path = event.data.name

    # 获取文件名
    file_name = file_path.split("/")[-1]

    # 下载文件到本地函数
    storage.bucket("testbucketinput").blob(
        "video.mp4").download_to_filename("video.mp4")
    storage.bucket("testbucketinput").blob(
        "audio.mp3").download_to_filename("audio.mp3")

    # 使用ffmpeg将音频添加到视频中
    cmd = f"ffmpeg -i video.mp4 -i audio.mp3 -c copy -map 0:v:0 -map 1:a:0 output.mp4"
    subprocess.run(cmd, shell=True)

    # 将最终的视频上传到输出存储桶
    storage.bucket("testbucketoutput").blob(
        "output.mp4").upload_from_filename("output.mp4")

希望这能帮助你解决问题。

英文:

Simple and easy, or so I thought. Firebase seems to make it really hard to edit videos, it will work in the emulator but not when you deploy or vice versa. I've been trying to simply add an audio file to a video using a function. Right now the output is there but 0 bytes.

Right now this is my test functions for this specific example:

It will give you a link, and assuming you have the files video.mp4 and audio.mp3 inside of testfiles folder, it will upload them to the input bucket, then to the trigger bucket to run the function to add those 2 files and output them to the output bucket. But ffmpeg doesnt always work, moviepy also doesnt always work, plus its too slow.

def addTestBuckets2(req: https_fn.Request) -&gt; https_fn.Response:
# create the buckets
testBucketInput = storage.bucket(&quot;testbucketinput&quot;)
testBucketOutput = storage.bucket(&quot;testbucketoutput&quot;)
testBucketTrigger = storage.bucket(&quot;testbuckettrigger&quot;)
# upload the test files
testBucketInput.blob(&quot;audio.mp3&quot;).upload_from_filename(
&quot;D:/backendfunctions/functions/testfiles/audio.mp3&quot;)
testBucketInput.blob(&quot;video.mp4&quot;).upload_from_filename(
&quot;D:/backendfunctions/functions/testfiles/video.mp4&quot;)
open(&quot;trigger.txt&quot;, &quot;w&quot;).close()
testBucketTrigger.blob(&quot;trigger.txt&quot;).upload_from_filename(
&quot;trigger.txt&quot;)
# try to download the output.mp4 from the bucket on a loop
keepTrying = 0
while keepTrying &lt; 100:
try:
testBucketOutput.blob(&quot;output.mp4&quot;).download_to_filename(
&quot;output.mp4&quot;)
break
except:
sleep(.1)
keepTrying += 1
# os.remove(&quot;output.mp4&quot;)
# return
return https_fn.Response(&quot;Bucket tested&quot;)
@storage_fn.on_object_finalized(bucket=&quot;testbuckettrigger&quot;, region=region)
def editvidtestfunction(event: storage_fn.CloudEvent[storage_fn.StorageObjectData | None],) -&gt; None:
&quot;&quot;&quot; Test functions editing limit &quot;&quot;&quot;
# get the file path from the event
file_path = event.data.name
# get the file name
file_name = file_path.split(&quot;/&quot;)[-1]
# just_path = file_path.split(&quot;/&quot;)[:-1][0]
# just_name = &#39;.&#39;.join(file_name.split(&#39;.&#39;)[:-1])
# donwload the file from the bucket to local function
storage.bucket(&quot;testbucketinput&quot;).blob(
&quot;video.mp4&quot;).download_to_filename(&quot;video.mp4&quot;)
storage.bucket(&quot;testbucketinput&quot;).blob(
&quot;audio.mp3&quot;).download_to_filename(&quot;audio.mp3&quot;)
# add the audio to the video using ffmpeg
cmd = f&quot;ffmpeg -i video.mp4 -i audio.mp3 -c copy -map 0:v:0 -map 1:a:0 output.mp4&quot;
subprocess.run(cmd, shell=True)
# upload the final video to the output bucket
storage.bucket(&quot;testbucketoutput&quot;).blob(
&quot;output.mp4&quot;).upload_from_filename(&quot;output.mp4&quot;)```
</details>
# 答案1
**得分**: 0
首先,您需要在Python中安装所需的包:
```python
pip install firebase-admin
pip install google-cloud-storage

接下来,设置您的Firebase Admin SDK。如果您没有现有项目,请创建一个新项目,并生成该项目的私钥,该私钥将在您的Python代码中使用。

然后,将您的媒体文件上传到云端。

接下来,使用Python库处理媒体文件,您可以使用Moviepy:

pip install moviepy

使用所选的库执行所需的视频和音频文件编辑操作。例如,您可以连接音频文件,将音频叠加到视频上,或根据需要调整时间戳。

保存编辑后的媒体文件到云端,不要忘记在处理完成后进行清理。

import firebase_admin
from firebase_admin import credentials
from firebase_admin import storage
from moviepy.editor import VideoFileClip, AudioFileClip

# 步骤2:设置Firebase Admin SDK
cred = credentials.Certificate("path/to/serviceAccountKey.json")
firebase_admin.initialize_app(cred, {
    'storageBucket': 'your-storage-bucket.appspot.com'
})

# 步骤3:将您的媒体文件上传到云存储
bucket = storage.bucket()
video_blob = bucket.blob("videos/sample_video.mp4")
audio_blob = bucket.blob("audios/sample_audio.wav")
video_blob.upload_from_filename("path/to/sample_video.mp4")
audio_blob.upload_from_filename("path/to/sample_audio.wav")

# 步骤4:处理视频和音频文件
video_path = video_blob.generate_signed_url(datetime.timedelta(seconds=1), method='GET')
audio_path = audio_blob.generate_signed_url(datetime.timedelta(seconds=3), method='GET')
video_clip = VideoFileClip(video_path)
audio_clip = AudioFileClip(audio_path)
final_clip = video_clip.set_audio(audio_clip)

# 步骤5:保存编辑后的媒体文件
final_clip.write_videofile("path/to/edited_video.mp4", codec="libx264")

# 步骤6:清理(可选)
video_blob.delete()
audio_blob.delete()

在代码中执行以下替换:

"path/to/serviceAccountKey.json":您的Firebase服务帐户密钥JSON文件的路径。

"your-storage-bucket.appspot.com":您的Firebase存储桶名称。

"videos/sample_video.mp4":云存储中视频文件的所需位置和文件名。

"audios/sample_audio.wav":云存储中音频文件的所需位置和文件名。

"path/to/sample_video.mp4":本地视频文件的路径。

"path/to/sample_audio.wav":本地音频文件的路径。

"path/to/edited_video.mp4":本地机器上编辑后的视频文件的所需位置和文件名。

英文:

Firstly You will need to install the required packages in Python:

pip install firebase-admin
pip install google-cloud-storage

Nextly setup your Firebase Admin SDK, create a new project if you do not have an existing one and generate a private key for that project which will be used in your python Code
Then Upload your media to the Cloud
Next process the media using Python Libraries, your can use Moviepy

pip install moviepy

Use the selected library to perform the required editing operations on the video and audio files.
For example, you can concatenate audio files, overlay audio onto the video, or adjust timestamps as needed.
Save your edited media file to the Cloud, don't forget to clean up after the process.

import firebase_admin
from firebase_admin import credentials
from firebase_admin import storage
from moviepy.editor import VideoFileClip, AudioFileClip
# Step 2: Set up the Firebase Admin SDK
cred = credentials.Certificate(&quot;path/to/serviceAccountKey.json&quot;)
firebase_admin.initialize_app(cred, {
&#39;storageBucket&#39;: &#39;your-storage-bucket.appspot.com&#39;
})
# Step 3: Upload your media files to Cloud Storage
bucket = storage.bucket()
video_blob = bucket.blob(&quot;videos/sample_video.mp4&quot;)
audio_blob = bucket.blob(&quot;audios/sample_audio.wav&quot;)
video_blob.upload_from_filename(&quot;path/to/sample_video.mp4&quot;)
audio_blob.upload_from_filename(&quot;path/to/sample_audio.wav&quot;)
# Step 4: Process the video and audio files
video_path = video_blob.generate_signed_url(datetime.timedelta(seconds=1), method=&#39;GET&#39;)
audio_path = audio_blob.generate_signed_url(datetime.timedelta(seconds=3), method=&#39;GET&#39;)
video_clip = VideoFileClip(video_path)
audio_clip = AudioFileClip(audio_path)
final_clip = video_clip.set_audio(audio_clip)
# Step 5: Save the edited media file
final_clip.write_videofile(&quot;path/to/edited_video.mp4&quot;, codec=&quot;libx264&quot;)
# Step 6: Clean up (optional)
video_blob.delete()
audio_blob.delete()

In the code do the following Replacements
&quot;path/to/serviceAccountKey.json&quot;: The path to your Firebase service account key JSON file.
&quot;your-storage-bucket.appspot.com&quot;: Your Firebase Storage bucket name.
&quot;videos/sample_video.mp4&quot;: The desired location and filename for your video file in Cloud Storage.
&quot;audios/sample_audio.wav&quot;: The desired location and filename for your audio file in Cloud Storage.
&quot;path/to/sample_video.mp4&quot;: The local path to your video file.
&quot;path/to/sample_audio.wav&quot;: The local path to your audio file.
&quot;path/to/edited_video.mp4&quot;: The desired location and filename for the edited video file on your local machine.

huangapple
  • 本文由 发表于 2023年6月5日 14:02:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/76403829.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定