小能豆

How to get the duration of an mp3 file in Golang?

go

I set up a text to speech an request that to openAI API then it generates an audio. Now I want to know it’s duration in [MM:SS], is there a way or a library to get it?


阅读 106

收藏
2023-12-20

共1个答案

小能豆

To determine the duration of an audio file, you can use a library that provides audio analysis capabilities. One such library is ffprobe, which is part of the FFmpeg suite. FFprobe is a command-line tool that comes with FFmpeg and is used for analyzing multimedia files.

Here’s a general approach using ffprobe in combination with a programming language like Python:

  1. Install FFmpeg: First, you need to install FFmpeg, which includes ffprobe. You can download it from the official FFmpeg website or use a package manager like apt or brew to install it.

  2. Run FFprobe from Python: Once FFmpeg is installed, you can use the subprocess module in Python to call ffprobe and parse its output to get the duration. Here’s a simple Python script:

```
import subprocess
import re

def get_audio_duration(file_path):
command = [‘ffprobe’, ‘-v’, ‘error’, ‘-show_entries’, ‘format=duration’, ‘-of’, ‘default=noprint_wrappers=1:nokey=1’, file_path]
duration_str = subprocess.check_output(command, universal_newlines=True).strip()
duration_seconds = float(duration_str)
return duration_seconds

def format_duration(duration_seconds):
minutes, seconds = divmod(duration_seconds, 60)
return f’{int(minutes):02}:{int(seconds):02}’

# Example usage
audio_file_path = ‘path/to/your/audio/file.mp3’
duration_seconds = get_audio_duration(audio_file_path)
formatted_duration = format_duration(duration_seconds)
print(f’The duration is: {formatted_duration}’)
```

Replace 'path/to/your/audio/file.mp3' with the actual path to your audio file.

This script uses subprocess to run ffprobe with the appropriate parameters and then parses the output to get the duration in seconds. The format_duration function is included to convert the duration from seconds to the desired [MM:SS] format.

Make sure to adapt the script based on your programming language or specific requirements.

2023-12-20