搜索
首页后端开发Python教程如何在Python中获取音频的持续时间?

如何在Python中获取音频的持续时间?

近年来,音频处理领域取得了显着的扩展,Python已成为处理围绕音频操作的任务的常见选择。在处理音频时,常见的任务之一是确定音频文件的长度,这在各种应用中都非常有用,例如创建播放列表、音频数据分析或开发音频编辑工具。

Throughout this article, you will be guided through a variety of techniques, ranging from the basic to the advanced, in order to obtain the duration of audio using Python. Real code examples will be provided along the way. Before delving deeper into the subject matter, it is crucial to gain an understanding of the fundamental concepts and terminology that pertain to audio processing. This will give you the necessary foundation to implement the various approaches presented later in the article. Let's start with the definition of audio duration and then explore the syntax and algorithms for calculating it.

“音频时长”一词指的是音频文件播放的时间长度,通常以秒或分钟为单位进行测量。这个值受到一系列定义音频文件的特征的影响,包括样本数量、声道和采样率。对这些知识的全面掌握对于各种应用非常重要,包括但不限于转录、分析和音频编辑。

Syntax

Python提供了各种各样的库来管理音频文件处理。这些库包括wave、pydub和librosa,每个库都有自己独特的语法和函数,用于上传音频文件和测量它们的时间长度。确定音频文件持续时间的典型过程包括以下步骤:

  • Importing the mandatory libraries.

  • 读取音频文件。

  • Extracting the file's characteristics (such as the sample rate, quantity of samples, and channel quantity).

  • Calculating the duration utilizing the extracted characteristics.

算法

要在Python中获取音频文件的持续时间,可以实现以下算法 -

  • Implement the appropriate library to upload the audio file.

  • 提取音频文件的相关特征,包括采样率、通道数量和帧数。

  • Calculate the audio file's duration by dividing the number of frames by the sample rate.

  • 通过打印或返回它来输出持续时间值。

Approaches

我们现在将探讨在Python中确定音频文件持续时间的几种技术。将介绍以下方法 −

  • 通过利用波浪库。

  • By using the pydub library.

  • 使用librosa库。

  • By using the ffmpeg-python library.

方法一:使用wave库

波浪库是Python的内置模块,提供对WAV文件的支持。这是一个完整的代码示例,演示如何使用波浪库获取音频文件的持续时间 -

Example

import wave
def get_duration_wave(file_path):
   with wave.open(file_path, 'r') as audio_file:
      frame_rate = audio_file.getframerate()
      n_frames = audio_file.getnframes()
      duration = n_frames / float(frame_rate)
      return duration
file_path = 'example.wav'
duration = get_duration_wave(file_path)
print(f"Duration: {duration:.2f} seconds")

Output

Duration: 10.00 seconds

Approach 2: Using the pydub library

The pydub library stands as a commonly used and simple-to-utilize tool for the manipulation of audio. In order to make use of pydub, you must first install it via pip install pydub. Here's a code example to get the duration using pydub −

Example

from pydub import AudioSegment
def get_duration_pydub(file_path):
   audio_file = AudioSegment.from_file(file_path)
   duration = audio_file.duration_seconds
   return duration
file_path = 'example.wav'
duration = get_duration_pydub(file_path)
print(f"Duration: {duration:.2f} seconds")

Output

Duration: 10.00 seconds

Within this particular code snippet, we import the AudioSegment class, which hails from the pydub library, with the purpose of reading and making alterations to audio files. To load the audio file, we call the from_file function, and the duration_seconds attribute is employed to acquire the length of the audio file in seconds.

使用librosa库的方法三:

Librosa stands as yet another esteemed library for the processing of audio using Python, putting its emphasis mainly on the analysis of music and sound. By typing 'pip install librosa' in your terminal or command prompt, you will be able to easily and quickly install it. Here's a code example to get the duration using librosa −

Example

import librosa
def get_duration_librosa(file_path):
   audio_data, sample_rate = librosa.load(file_path)
   duration = librosa.get_duration(y=audio_data, sr=sample_rate)
   return duration
file_path = 'example.wav'
duration = get_duration_librosa(file_path)
print(f"Duration: {duration:.2f} seconds")

Output

Duration: 10.00 seconds

在这个例子中,使用librosa.load函数来读取音频文件并获取音频数据和采样率。然后,利用librosa.get_duration函数基于音频数据和采样率来计算持续时间。

Approach 4: Using the ffmpeg-python library

FFmpeg是在各种平台上常用的用于处理音频和视频的工具。 ffmpeg-python库充当了FFmpeg命令行界面的Python包装器,并可以使用pip install ffmpeg-python进行安装。以下是一个示例代码,演示了如何使用ffmpeg-python获取音频文件的持续时间−

Example

import ffmpeg
def get_duration_ffmpeg(file_path):
   probe = ffmpeg.probe(file_path)
   stream = next((stream for stream in probe['streams'] if stream['codec_type'] == 'audio'), None)
   duration = float(stream['duration'])
   return duration
file_path = 'example.wav'
duration = get_duration_ffmpeg(file_path)
print(f"Duration: {duration:.2f} seconds")

Output

Duration: 10.00 seconds

在这个例子中,我们使用ffmpeg.probe函数来获取与音频文件相关的元数据。随后,我们从流列表中过滤出音频流,并从流字典中提取出'duration'字段中的持续时间。

结论

在本文中,我们深入探讨了使用wave、pydub、librosa和ffmpeg-python库在Python中获取音频文件时长的四种不同方法。每种方法都有其自身的优点和限制,库的选择取决于您个人的需求和偏好。这些代码示例旨在为您提供在Python项目中实现音频时长计算的坚实基础。

以上是如何在Python中获取音频的持续时间?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文转载于:tutorialspoint。如有侵权,请联系admin@php.cn删除
Python和时间:充分利用您的学习时间Python和时间:充分利用您的学习时间Apr 14, 2025 am 12:02 AM

要在有限的时间内最大化学习Python的效率,可以使用Python的datetime、time和schedule模块。1.datetime模块用于记录和规划学习时间。2.time模块帮助设置学习和休息时间。3.schedule模块自动化安排每周学习任务。

Python:游戏,Guis等Python:游戏,Guis等Apr 13, 2025 am 12:14 AM

Python在游戏和GUI开发中表现出色。1)游戏开发使用Pygame,提供绘图、音频等功能,适合创建2D游戏。2)GUI开发可选择Tkinter或PyQt,Tkinter简单易用,PyQt功能丰富,适合专业开发。

Python vs.C:申请和用例Python vs.C:申请和用例Apr 12, 2025 am 12:01 AM

Python适合数据科学、Web开发和自动化任务,而C 适用于系统编程、游戏开发和嵌入式系统。 Python以简洁和强大的生态系统着称,C 则以高性能和底层控制能力闻名。

2小时的Python计划:一种现实的方法2小时的Python计划:一种现实的方法Apr 11, 2025 am 12:04 AM

2小时内可以学会Python的基本编程概念和技能。1.学习变量和数据类型,2.掌握控制流(条件语句和循环),3.理解函数的定义和使用,4.通过简单示例和代码片段快速上手Python编程。

Python:探索其主要应用程序Python:探索其主要应用程序Apr 10, 2025 am 09:41 AM

Python在web开发、数据科学、机器学习、自动化和脚本编写等领域有广泛应用。1)在web开发中,Django和Flask框架简化了开发过程。2)数据科学和机器学习领域,NumPy、Pandas、Scikit-learn和TensorFlow库提供了强大支持。3)自动化和脚本编写方面,Python适用于自动化测试和系统管理等任务。

您可以在2小时内学到多少python?您可以在2小时内学到多少python?Apr 09, 2025 pm 04:33 PM

两小时内可以学到Python的基础知识。1.学习变量和数据类型,2.掌握控制结构如if语句和循环,3.了解函数的定义和使用。这些将帮助你开始编写简单的Python程序。

如何在10小时内通过项目和问题驱动的方式教计算机小白编程基础?如何在10小时内通过项目和问题驱动的方式教计算机小白编程基础?Apr 02, 2025 am 07:18 AM

如何在10小时内教计算机小白编程基础?如果你只有10个小时来教计算机小白一些编程知识,你会选择教些什么�...

如何在使用 Fiddler Everywhere 进行中间人读取时避免被浏览器检测到?如何在使用 Fiddler Everywhere 进行中间人读取时避免被浏览器检测到?Apr 02, 2025 am 07:15 AM

使用FiddlerEverywhere进行中间人读取时如何避免被检测到当你使用FiddlerEverywhere...

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

AI Hentai Generator

AI Hentai Generator

免费生成ai无尽的。

热门文章

R.E.P.O.能量晶体解释及其做什么(黄色晶体)
3 周前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳图形设置
3 周前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您听不到任何人,如何修复音频
3 周前By尊渡假赌尊渡假赌尊渡假赌
WWE 2K25:如何解锁Myrise中的所有内容
4 周前By尊渡假赌尊渡假赌尊渡假赌

热工具

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

功能强大的PHP集成开发环境

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

将Eclipse与SAP NetWeaver应用服务器集成。

EditPlus 中文破解版

EditPlus 中文破解版

体积小,语法高亮,不支持代码提示功能