Reputation: 55
How can i convert Mp3 file to custom sample data using bass library in C# ? custom means i want result in a certain properties for example mono and 5000hz! i try this code before but it does not works!
public float[] ReadMonoFromFile(string filename, int samplerate, int milliseconds, int startmillisecond) {
int totalmilliseconds = milliseconds <= 0 ? Int32.MaxValue : milliseconds + startmillisecond; float[] data = null; //create streams for re-sampling int stream = Bass.BASS_StreamCreateFile(filename, 0, 0, BASSFlag.BASS_STREAM_DECODE | BASSFlag.BASS_SAMPLE_MONO | BASSFlag.BASS_SAMPLE_FLOAT); //Decode the stream if (stream == 0) throw new Exception(Bass.BASS_ErrorGetCode().ToString()); int mixerStream = BassMix.BASS_Mixer_StreamCreate(samplerate, 1, BASSFlag.BASS_STREAM_DECODE | BASSFlag.BASS_SAMPLE_MONO | BASSFlag.BASS_SAMPLE_FLOAT); if (mixerStream == 0) throw new Exception(Bass.BASS_ErrorGetCode().ToString()); if (BassMix.BASS_Mixer_StreamAddChannel(mixerStream, stream, BASSFlag.BASS_MIXER_FILTER)) { int bufferSize = samplerate * 10 * 4; /*read 10 seconds at each iteration*/ float[] buffer = new float[bufferSize]; List<float[]> chunks = new List<float[]>(); int size = 0; while ((float) (size)/samplerate*1000 < totalmilliseconds) { //get re-sampled/mono data int bytesRead = Bass.BASS_ChannelGetData(mixerStream, buffer, bufferSize); if (bytesRead == 0) break; float[] chunk = new float[bytesRead/4]; //each float contains 4 bytes Array.Copy(buffer, chunk, bytesRead/4); chunks.Add(chunk); size += bytesRead/4; //size of the data } if ((float) (size)/samplerate*1000 < (milliseconds + startmillisecond)) return null; /*not enough samples to return the requested data*/ int start = (int) ((float) startmillisecond*samplerate/1000); int end = (milliseconds <= 0) ? size : (int) ((float) (startmillisecond + milliseconds)*samplerate/1000); data = new float[size]; int index = 0; /*Concatenate*/ foreach (float[] chunk in chunks) { Array.Copy(chunk, 0, data, index, chunk.Length); index += chunk.Length; } /*Select specific part of the song*/ if (start != 0 || end != size) { float[] temp = new float[end - start]; Array.Copy(data, start, temp, 0, end - start); data = temp; } } else throw new Exception(Bass.BASS_ErrorGetCode().ToString()); return data; }
i called this function like this:
float[] pcm = ReadMonoFromFile(Path.GetFullPath("1.mp3"), 0, 0, 0);
but in throws this exception :The type initializer for 'Un4seen.Bass.Bass' threw an exception.
Upvotes: 1
Views: 2475