73 lines
2.5 KiB
C#
73 lines
2.5 KiB
C#
using System;
|
|
using System.IO;
|
|
using JD.LogService;
|
|
using NAudio.Wave;
|
|
using TeaBox.Macros;
|
|
|
|
namespace JDSongConverter.Tasks
|
|
{
|
|
/// <summary>
|
|
/// Checks the samplerate of a wave file and change it if necessary
|
|
/// </summary>
|
|
class ChangeWaveSamplerateTask : Task
|
|
{
|
|
public string InputFile { get; set; }
|
|
public string OutputFile { get; set; }
|
|
|
|
private const int RequestedSamplerate = 48000;
|
|
|
|
public void Init(string inputFile, string outputFile)
|
|
{
|
|
InputFile = inputFile;
|
|
OutputFile = outputFile;
|
|
}
|
|
|
|
public override string Name
|
|
{
|
|
get { return String.Format("Ensure wave samplerate is {0}", RequestedSamplerate); }
|
|
set { }
|
|
}
|
|
|
|
public override string ProgressText
|
|
{
|
|
get { return String.Format("Checking samplerate of wave file '{0}'", InputFile); }
|
|
}
|
|
|
|
public override TaskResult Process(IExecutionContext executionContext)
|
|
{
|
|
if (string.IsNullOrEmpty(InputFile) || !File.Exists(InputFile))
|
|
return TaskResult.ParametersError;
|
|
|
|
string tempFile = System.IO.Path.ChangeExtension(InputFile, ".tmp");
|
|
|
|
using (var reader = new CueWaveFileReader(InputFile))
|
|
{
|
|
if (reader.WaveFormat.SampleRate == RequestedSamplerate)
|
|
{
|
|
executionContext.LogMessage("No need to change wave samplerate.");
|
|
return TaskResult.Ok;
|
|
}
|
|
|
|
var targetFormat = new WaveFormat(RequestedSamplerate, reader.WaveFormat.Channels);
|
|
|
|
using (var waveFormatConversionStream = new WaveFormatConversionStream(targetFormat, reader))
|
|
{
|
|
using (var writer = new CueWaveFileWriter(tempFile, targetFormat))
|
|
{
|
|
int bufferSize = waveFormatConversionStream.BlockAlign * 1024 * 4;
|
|
waveFormatConversionStream.CopyTo(writer, bufferSize);
|
|
double sampleRateFactor = targetFormat.SampleRate/(double)reader.WaveFormat.SampleRate;
|
|
foreach (Cue cue in reader.Cues)
|
|
{
|
|
writer.AddCue((int)(cue.Position * sampleRateFactor), cue.Label);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
File.Move(tempFile, OutputFile);
|
|
|
|
return TaskResult.Ok;
|
|
}
|
|
|
|
}
|
|
}
|