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

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

add an audio to a video on Firebase using python

问题

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

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

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

  1. @https_fn.on_request(region="europe-west2", memory=1024)
  2. def addTestBuckets2(req: https_fn.Request) -> https_fn.Response:
  3. # 创建存储桶
  4. testBucketInput = storage.bucket("testbucketinput")
  5. testBucketOutput = storage.bucket("testbucketoutput")
  6. testBucketTrigger = storage.bucket("testbuckettrigger")
  7. # 上传测试文件
  8. testBucketInput.blob("audio.mp3").upload_from_filename(
  9. "D:/backendfunctions/functions/testfiles/audio.mp3")
  10. testBucketInput.blob("video.mp4").upload_from_filename(
  11. "D:/backendfunctions/functions/testfiles/video.mp4")
  12. open("trigger.txt", "w").close()
  13. testBucketTrigger.blob("trigger.txt").upload_from_filename(
  14. "trigger.txt")
  15. # 尝试从存储桶中循环下载output.mp4文件
  16. keepTrying = 0
  17. while keepTrying < 100:
  18. try:
  19. testBucketOutput.blob("output.mp4").download_to_filename(
  20. "output.mp4")
  21. break
  22. except:
  23. sleep(.1)
  24. keepTrying += 1
  25. # os.remove("output.mp4")
  26. # 返回响应
  27. return https_fn.Response("Bucket tested")
  28. @storage_fn.on_object_finalized(bucket="testbuckettrigger", region=region)
  29. def editvidtestfunction(event: storage_fn.CloudEvent[storage_fn.StorageObjectData | None],) -> None:
  30. """测试编辑函数的限制"""
  31. # 从事件中获取文件路径
  32. file_path = event.data.name
  33. # 获取文件名
  34. file_name = file_path.split("/")[-1]
  35. # 下载文件到本地函数
  36. storage.bucket("testbucketinput").blob(
  37. "video.mp4").download_to_filename("video.mp4")
  38. storage.bucket("testbucketinput").blob(
  39. "audio.mp3").download_to_filename("audio.mp3")
  40. # 使用ffmpeg将音频添加到视频中
  41. cmd = f"ffmpeg -i video.mp4 -i audio.mp3 -c copy -map 0:v:0 -map 1:a:0 output.mp4"
  42. subprocess.run(cmd, shell=True)
  43. # 将最终的视频上传到输出存储桶
  44. storage.bucket("testbucketoutput").blob(
  45. "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.

  1. def addTestBuckets2(req: https_fn.Request) -&gt; https_fn.Response:
  2. # create the buckets
  3. testBucketInput = storage.bucket(&quot;testbucketinput&quot;)
  4. testBucketOutput = storage.bucket(&quot;testbucketoutput&quot;)
  5. testBucketTrigger = storage.bucket(&quot;testbuckettrigger&quot;)
  6. # upload the test files
  7. testBucketInput.blob(&quot;audio.mp3&quot;).upload_from_filename(
  8. &quot;D:/backendfunctions/functions/testfiles/audio.mp3&quot;)
  9. testBucketInput.blob(&quot;video.mp4&quot;).upload_from_filename(
  10. &quot;D:/backendfunctions/functions/testfiles/video.mp4&quot;)
  11. open(&quot;trigger.txt&quot;, &quot;w&quot;).close()
  12. testBucketTrigger.blob(&quot;trigger.txt&quot;).upload_from_filename(
  13. &quot;trigger.txt&quot;)
  14. # try to download the output.mp4 from the bucket on a loop
  15. keepTrying = 0
  16. while keepTrying &lt; 100:
  17. try:
  18. testBucketOutput.blob(&quot;output.mp4&quot;).download_to_filename(
  19. &quot;output.mp4&quot;)
  20. break
  21. except:
  22. sleep(.1)
  23. keepTrying += 1
  24. # os.remove(&quot;output.mp4&quot;)
  25. # return
  26. return https_fn.Response(&quot;Bucket tested&quot;)
  27. @storage_fn.on_object_finalized(bucket=&quot;testbuckettrigger&quot;, region=region)
  28. def editvidtestfunction(event: storage_fn.CloudEvent[storage_fn.StorageObjectData | None],) -&gt; None:
  29. &quot;&quot;&quot; Test functions editing limit &quot;&quot;&quot;
  30. # get the file path from the event
  31. file_path = event.data.name
  32. # get the file name
  33. file_name = file_path.split(&quot;/&quot;)[-1]
  34. # just_path = file_path.split(&quot;/&quot;)[:-1][0]
  35. # just_name = &#39;.&#39;.join(file_name.split(&#39;.&#39;)[:-1])
  36. # donwload the file from the bucket to local function
  37. storage.bucket(&quot;testbucketinput&quot;).blob(
  38. &quot;video.mp4&quot;).download_to_filename(&quot;video.mp4&quot;)
  39. storage.bucket(&quot;testbucketinput&quot;).blob(
  40. &quot;audio.mp3&quot;).download_to_filename(&quot;audio.mp3&quot;)
  41. # add the audio to the video using ffmpeg
  42. cmd = f&quot;ffmpeg -i video.mp4 -i audio.mp3 -c copy -map 0:v:0 -map 1:a:0 output.mp4&quot;
  43. subprocess.run(cmd, shell=True)
  44. # upload the final video to the output bucket
  45. storage.bucket(&quot;testbucketoutput&quot;).blob(
  46. &quot;output.mp4&quot;).upload_from_filename(&quot;output.mp4&quot;)```
  47. </details>
  48. # 答案1
  49. **得分**: 0
  50. 首先,您需要在Python中安装所需的包:
  51. ```python
  52. pip install firebase-admin
  53. pip install google-cloud-storage

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

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

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

  1. pip install moviepy

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

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

  1. import firebase_admin
  2. from firebase_admin import credentials
  3. from firebase_admin import storage
  4. from moviepy.editor import VideoFileClip, AudioFileClip
  5. # 步骤2:设置Firebase Admin SDK
  6. cred = credentials.Certificate("path/to/serviceAccountKey.json")
  7. firebase_admin.initialize_app(cred, {
  8. 'storageBucket': 'your-storage-bucket.appspot.com'
  9. })
  10. # 步骤3:将您的媒体文件上传到云存储
  11. bucket = storage.bucket()
  12. video_blob = bucket.blob("videos/sample_video.mp4")
  13. audio_blob = bucket.blob("audios/sample_audio.wav")
  14. video_blob.upload_from_filename("path/to/sample_video.mp4")
  15. audio_blob.upload_from_filename("path/to/sample_audio.wav")
  16. # 步骤4:处理视频和音频文件
  17. video_path = video_blob.generate_signed_url(datetime.timedelta(seconds=1), method='GET')
  18. audio_path = audio_blob.generate_signed_url(datetime.timedelta(seconds=3), method='GET')
  19. video_clip = VideoFileClip(video_path)
  20. audio_clip = AudioFileClip(audio_path)
  21. final_clip = video_clip.set_audio(audio_clip)
  22. # 步骤5:保存编辑后的媒体文件
  23. final_clip.write_videofile("path/to/edited_video.mp4", codec="libx264")
  24. # 步骤6:清理(可选)
  25. video_blob.delete()
  26. 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:

  1. pip install firebase-admin
  2. 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

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

  1. import firebase_admin
  2. from firebase_admin import credentials
  3. from firebase_admin import storage
  4. from moviepy.editor import VideoFileClip, AudioFileClip
  5. # Step 2: Set up the Firebase Admin SDK
  6. cred = credentials.Certificate(&quot;path/to/serviceAccountKey.json&quot;)
  7. firebase_admin.initialize_app(cred, {
  8. &#39;storageBucket&#39;: &#39;your-storage-bucket.appspot.com&#39;
  9. })
  10. # Step 3: Upload your media files to Cloud Storage
  11. bucket = storage.bucket()
  12. video_blob = bucket.blob(&quot;videos/sample_video.mp4&quot;)
  13. audio_blob = bucket.blob(&quot;audios/sample_audio.wav&quot;)
  14. video_blob.upload_from_filename(&quot;path/to/sample_video.mp4&quot;)
  15. audio_blob.upload_from_filename(&quot;path/to/sample_audio.wav&quot;)
  16. # Step 4: Process the video and audio files
  17. video_path = video_blob.generate_signed_url(datetime.timedelta(seconds=1), method=&#39;GET&#39;)
  18. audio_path = audio_blob.generate_signed_url(datetime.timedelta(seconds=3), method=&#39;GET&#39;)
  19. video_clip = VideoFileClip(video_path)
  20. audio_clip = AudioFileClip(audio_path)
  21. final_clip = video_clip.set_audio(audio_clip)
  22. # Step 5: Save the edited media file
  23. final_clip.write_videofile(&quot;path/to/edited_video.mp4&quot;, codec=&quot;libx264&quot;)
  24. # Step 6: Clean up (optional)
  25. video_blob.delete()
  26. 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:

确定