Reputation:
I'm making a XNA 4.0 game, and I'm using NAudio for playing sounds because it is more powerful than XNA's Sound module.
I need to play a MP3 file slower (either at 0.75x or 0.5x speed). My original idea was to change the Sample Rate of the WaveStream. Here is what I'm trying to do:
WaveStream originalWaveStream = new MP3FileReader(filepath);
WaveChannel32 volumeStream = new WaveChannel32(originalWaveStream); //So I can change the volume of the playback
WaveFormat tempFormat = new WaveFormat((int)(volumeStream.WaveFormat.SampleRate * 0.75f),(int)volumeStream.WaveFormat.BitsPerSample,(int)volumeStream.WaveFormat.Channels);
WaveFormatConversionStream tempStream = new WaveFormatConversionStream(tempFormat, volumeStream);
WaveChannel32 slowerWaveStream = new WaveChannel32(tempStream);
If I run this, I get an MmException that says "AcmNotPossible calling acmStreamOpen" when the tempStream's constructor is running.
What I am doing wrong? Is changing the Sample Rate the only way to change the playback speed? Is there a correct way to do it?
Upvotes: 1
Views: 2338
Reputation: 49482
You would need to implement a playback speed algorithm, which NAudio does not supply.
The reason your code does not work is because volumeStream is an IEEE float WaveFormat, and you are asking the ACM resampler to output 32 bit PCM with float input which it can't do. If you used WaveFormat.CreateIEEEFloatFormat for tempFormat then this would probably 'work'. However, as well as changing the playback speed, you'd also be pitch shifting, so this is not an ideal solution. You could follow it by another pitch shift to compensate, but there are other problems with this approach (such as losing or aliasing part of your frequency spectrum during the resampling).
Yuval Naveh's open source Practice# uses NAudio and implements variable speed playback. He does it by wrapping SoundTouch, which is an open-source library that can perform time ("tempo") stretch. This should give good results and will be much easier than trying to write your own algorithm.
Upvotes: 2