Mix two audio files using NAudio - c#

I need to make noise on one audio file. I have the first audio (data) and the second audio (noise). How to put noise on the first audio so that it is looped. Or, if the first audio is shorter than the audio noise, then the result was the duration of the first audio.
I gave an example of their tutorial. But there is simply an overlay of one file on another. Without the possibility of looping and length optimization
using(var reader1 = new AudioFileReader("file1.wav"))
using(var reader2 = new AudioFileReader("file2.wav"))
{
var mixer = new MixingSampleProvider(new[] { reader1, reader2 });
WaveFileWriter.CreateWaveFile16("mixed.wav", mixer);
}

You could use a looping technique like the one I describe here to loop the shorter file (would then need to follow that with a ToSampleProvider).
And then use the Take extension method on your MixingSampleProvider to ensure you only read the duration of the longer file, so you don't create an infinitely large WAV file.

Related

Audio stream for multiple outputs (single producer, multi-consumer)

I am attempting to propagate a single sound source to multiple outputs (such as one microphone input to multiple sound cards or channels). The output does not have to be sync'd (a few ms delay is acceptable) but it would be nice if it could be sync'd.
I have successfully written code that loops a microphone input to an output using a WaveIn, a BufferedWaveProvider, and a WaveOut. However when I try to read one BufferedWaveProvider with two instances of WaveOut, the two outputs create this odd 'interleaved' choppy sound. Here is a code snippet for the output portion;
private void CreateWaveOutDevice()
{
waveProvider = new BufferedWaveProvider(waveIn.WaveFormat);
waveOut = new WaveOut();
waveOut.DeviceNumber = 0; //Sound card 1
waveOut.DesiredLatency = 100;
waveOut.Init(waveProvider);
waveOut.PlaybackStopped += wavePlayer_PlaybackStopped;
waveOut2 = new WaveOut();
waveOut2.DeviceNumber = 1; //Sound card 2
waveOut2.DesiredLatency = 100;
waveOut2.Init(waveProvider);
waveOut2.PlaybackStopped += wavePlayer_PlaybackStopped;
waveOut.Play();
waveOut2.Play();
}
I think the reason this is happening is because when the waveProvider circular buffer is read, the data is deleted so the two read methods are 'fighting' over the data which results in the choppy sound.
So I really have two questions;
1.) I see the Naudio library contains many types of waveStreams (RawSourceWaveStream is particularly interesting) However, I have been unable to find a good example of how to read a single stream with multiple waveOut methods. I have also been unable to create working code using waveStream with multiple outputs. Is anyone familiar with waveStreams and knows if this is something that can be done?
2.) If the Naudio wave streams cannot be used in a single producer multiple consumer situation then I believe I would need to make a circular buffer that is not cleared on a read, but only when the buffer is full and new data is pushed in. The code won't care if the data was read or not it just keeps filling the buffer. Would this be the correct approach?
I've spent days searching so hopefully this hasn't already been asked. Thanks for reading.
If you're just reading from a microphone and want two WaveOut's to play it, then the simple option is to create two BufferedWaveProviders, one for each WaveOut, and then when audio is received, send it to both.
Likewise if you were playing from an audio file to two soundcards, the easiest way is to use two reader objects and start them both separately.
There is unfortunately no easy way to synchronize, short of starting and stopping both players at the same time.
There are a few more advanced ways to try to split off an audio stream to two readers, but there can be complications especially if the two readers are not able to read at roughly the same rate.

C# Change decibels (volume) in audio file

I'm really new in NAudio and need your help. I'm working with NAudio and I need to change volume lvl in the audio file and write to a new file. I think I have to get samples of audio file and the increase something in them. But I don't know how to start. May anyone help me?
This is my code:
using (WaveFileReader reader = new WaveFileReader(inFile))
{
VolumeWaveProvider16 volumeProvider = new VolumeWaveProvider16(reader);
using (WaveFileWriter writer = new WaveFileWriter(outFile, reader.WaveFormat))
{
while (true)
{
var frame = reader.ReadNextSampleFrame();
if (frame == null)
break;
//var a = frame[0];
writer.WriteSample(frame[0] + 0.2f);
}
}
}
Am I doing all right?
If you have access to the PCM data, the simplest way is to increase each sample value by a constant.
Your example looks good. Have you tried comparing the old and the new WAV by listening to both?
A few things to note though:
ReadNextSampleFrame() returns an array of floats with one value for each audio channel. If you have multi-channel audio you should iterate over the array with foreach and increase each value of the frame.
Depending on the range of the retrieved sample values, adding 0.2 might have no effect. Have you checked what sort of values ReadNextSampleFrame() returns? I.e. when you debug your application, what are the actual values you are retrieving? Are there some (or a lot) values bigger than 1?
Since you do not know the range of your input values, you cannot clip them to that range. If a sample value is quite loud in the original file, increasing it might exceed the valid range which in turn might result in unexpected outputs.

Getting Audio Data From MP3 File using NAudio

I want to be able to get audio data from an MP3 file with NAudio, average out the data in the left and right channels to create one dataset and then resample the averaged 44.1KHz audio data to 8Khz but I am having trouble understanding how data is represented in an NAudio Wavestream.
If I had 1 sec worth of MP3 audio, then how many bytes would I have in the WaveStream? By looking at a few code samples it seems one sample is 4 bytes and audio is sampled at 44100Hz and we have 2 different channels, so would that mean we would have (44100 * 4 * 2) bytes in the wavestream, is that right?
Which of the following 3 streams - AStream,PCM and inputStream - should I use to get audio data from? And how to I access left and right channel data separately?
var AStream = new MP3FileReader(myFilePath);
var PCM = new WaveConversionStream.Createpcm(AStream);
var inputStream = new WaveChannel32(new BlockAlignStream(PCM));
I have been thinking of converting the WaveStream using the WaveFormatConversionStream but the code below throws a NAudio.MmException with a message saying "AcmNotPossible calling Acmstreamopen".
var targetFormat = new WaveFormat(8000,1);
var resampled = new WaveFormatConversionStream(targetFormat, inputStream);
The above code doesn't even work if targetFormat is equal to inputStream's format, so I don't know what I am doing wrong here.
//Still throws NAudio.MmException
var resampled = new WaveFormatConversionStream(inputStream.WaveFormat, inputStream);
Other Info: VS2012, WPF, NAudio 1.6.
You seem to have copied a code sample that belongs to a much earlier version of NAudio. The Mp3FileReader class will emit 16 bit samples, and uses the ACM MP3 frame decompressor by default. If you'd prefer your samples directly in floating point, then you can make use of the AudioFileReader.
Resampling 44.1kHz straight down to 8kHz is not a particularly good idea, as you'd end up with a lot of aliasing, so a low pass filter would ideally be applied first. Left and right channels are stored interleaved, so you get a left sample, followed by a right sample, and so on.

video not playing completly after join operation

This following is a code to join two videos. When I run the program it joins two videos and puts joined video in a folder. The joined video size is correct as it should be.
But when I play the video it plays the first part of the video in WMP but when i play the video in VLC it plays the second part of video.
public void JoiningVideo()
{
string j = #"D:/test2";
string outputpath = #"D:/test3/beforeEventab1.wmv";
DirectoryInfo di = new DirectoryInfo(j);
FileStream fs;
fs = new FileStream(outputpath, FileMode.Append);
foreach (FileInfo fi in di.GetFiles(#"*.wmv"))
{
byte[] bytesource = System.IO.File.ReadAllBytes(fi.FullName);
fs.Write(bytesource, 0, bytesource.Length);
}
fs.Close();
}
You know that each video-file starts with something called "header" ?
This part of the file contains information about the length etc.
If you want to join to seperate video files, you have to merge the headers to a new one containing information about both (joined) parts and to make sure that both videos fit to each other. (*)
Otherwise the video is not a valid file.
Due to the differences of the decoders of WMP and VLC, one recognises the first and the other one recognises the second file.
You can be lucky of that the the programs even played this 'corrupt' file! ;)
Just ask a search engine about merge wmv for a solution that should work for you!
(*)
To merge two videos they need to have
The same format (e.g. Resolution, Framerate, Bitrate)
If this does not apply, at least one of them has to be converted to match the other video
The videos have to be 'glued' together, it is not sufficient to append one's data to the other one.
Each video starts with a header. This header has to be changed to comprise information about the new (joined) video.
Also the raw image data cannot be simply appended. Every image is like a piece of a puzzle fitting to the next image in the video. The transition is like a new piece of a puzzle that has to be created. It may even be necessary to change/reorder the whole second file in order to get a working transition.
I am not a specialist, but at leas I can tell you, that this procedure is different for each type (MPEG, WMV, ..) of video. The best approach is to use an existing library for this purpose.

How do I merge/join MP3 files with C#?

I have a library of different words/phrases, and in order to build sentences at present I add a combination of these phrases into a playlist to make a sentence. Unfortunately if the user is running CPU intensive applications (which most of my users are) there can be a lag of a few seconds mid-sentence (in between phrases).
In order to combat this I was thinking of an approach which will merge the right combination of MP3 files on the fly into an appropriate phrase, save this in the %temp% directory, and then play this 1 MP3 file which should overcome the problem I'm experiencing with gaps.
What is the easiest way to do this in C#? Is there an easy way to do this? The files are fairly small, 3-4 seconds long each, and a sentence can consist of 3-20ish phrases.
here's how you can concatenate MP3 files using NAudio:
public static void Combine(string[] inputFiles, Stream output)
{
foreach (string file in inputFiles)
{
Mp3FileReader reader = new Mp3FileReader(file);
if ((output.Position == 0) && (reader.Id3v2Tag != null))
{
output.Write(reader.Id3v2Tag.RawData, 0, reader.Id3v2Tag.RawData.Length);
}
Mp3Frame frame;
while ((frame = reader.ReadNextFrame()) != null)
{
output.Write(frame.RawData, 0, frame.RawData.Length);
}
}
}
see here for more info
MP3 files consist of "frames", that each represent a short snippet (I think around 25 ms) of audio.
So yes, you can just concatenate them without a problem.
As MP3s are a compressed audio source, I imagine that you can't just concatenate them into a single file without decoding each one first to the wave form that it would play. This may be quite intensive. Perhaps you could cheat by using a critical section when playing back your phrase so that the CPU is not stolen from you until the phrase was complete. This isn't necessarily playing nice with other threads but might work if your phrases are short.
On simple option is to shell to the command line:
copy /b *.mp3 c:\new.mp3
Better would be to concatenate the streams. That's been answered here:
What would be the fastest way to concatenate three files in C#?

Categories

Resources