90 lines
2.9 KiB
PowerShell
90 lines
2.9 KiB
PowerShell
<#
|
|
.SYNOPSIS
|
|
Extracts audio in either WAV or MP3 format from a video file.
|
|
.PARAMETER Video
|
|
Path to the input video file. Can be absolute or relative to current directory.
|
|
.PARAMETER Output
|
|
Path to the output audio file. By default, the output file name is derived from the video file name.
|
|
.PARAMETER MP3
|
|
When present, extracts audio in MP3 format instead of WAV. Always uses best audio quality at 320 kbps.
|
|
.DESCRIPTION
|
|
This script uses ffmpeg to extract audio from a video file in either WAV or MP3 format using ffmpeg.
|
|
If the video file has no audio, then no output file is created and a message is displayed.
|
|
.NOTES
|
|
Requires ffmpeg to be installed and available in the system PATH.
|
|
#>
|
|
[CmdletBinding(SupportsShouldProcess)]
|
|
param(
|
|
[Parameter(Mandatory = $true)]
|
|
[string]$Video,
|
|
|
|
[Parameter(Mandatory = $false)]
|
|
[string]$Output,
|
|
|
|
[Parameter(Mandatory = $false)]
|
|
[switch]$MP3
|
|
)
|
|
|
|
try {
|
|
if (-not (Test-Path $Video)) {
|
|
throw "Video file not found: $Video"
|
|
}
|
|
|
|
$videoPath = Resolve-Path $Video
|
|
Write-Host "Processing video: $videoPath"
|
|
|
|
$ffprobe = Get-Command ffprobe -ErrorAction SilentlyContinue
|
|
if (-not $ffprobe) {
|
|
throw "ffprobe not found in PATH. Please install ffmpeg."
|
|
}
|
|
|
|
$ffprobeOutput = & ffprobe -v error -select_streams a:0 -show_entries stream=codec_type -of default=noprint_wrappers=1:nokey=1 $videoPath 2>&1
|
|
|
|
if ($ffprobeOutput -ne 'audio') {
|
|
Write-Host "No audio stream found in video file." -ForegroundColor Yellow
|
|
exit 0
|
|
}
|
|
|
|
if ([string]::IsNullOrEmpty($Output)) {
|
|
$videoBaseName = [System.IO.Path]::GetFileNameWithoutExtension($videoPath)
|
|
$videoDir = [System.IO.Path]::GetDirectoryName($videoPath)
|
|
|
|
if ($MP3) {
|
|
$Output = Join-Path $videoDir "$videoBaseName.mp3"
|
|
}
|
|
else {
|
|
$Output = Join-Path $videoDir "$videoBaseName.wav"
|
|
}
|
|
}
|
|
|
|
$outputPath = $Output
|
|
if (-not [System.IO.Path]::IsPathRooted($outputPath)) {
|
|
$outputPath = Join-Path (Get-Location).Path $outputPath
|
|
}
|
|
|
|
if ($PSCmdlet.ShouldProcess($outputPath, 'Extract audio from video')) {
|
|
Write-Host "Extracting audio to: $outputPath"
|
|
|
|
if ($MP3) {
|
|
ffmpeg -i $videoPath -vn -acodec libmp3lame -b:a 320k $outputPath -y -loglevel error
|
|
}
|
|
else {
|
|
ffmpeg -i $videoPath -vn -acodec pcm_s16le -ar 48000 $outputPath -y -loglevel error
|
|
}
|
|
|
|
if ($LASTEXITCODE -ne 0) {
|
|
throw "ffmpeg failed to extract audio with exit code $LASTEXITCODE"
|
|
}
|
|
|
|
if (-not (Test-Path $outputPath)) {
|
|
throw "Output audio file was not created: $outputPath"
|
|
}
|
|
|
|
Write-Host "Audio extracted successfully: $outputPath" -ForegroundColor Green
|
|
}
|
|
}
|
|
catch {
|
|
Write-Error "Error: $_"
|
|
exit 1
|
|
}
|