使用低音库解码mp3文件

时间:2013-05-02 17:34:55

标签: c# bass

如何使用C#中的低音库将Mp3文件转换为自定义样本数据? 自定义意味着我想要产生某些属性,例如mono和5000hz! 我之前尝试过此代码,但它不起作用!

  

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; }

我这样调用了这个函数:

  

float [] pcm = ReadMonoFromFile(Path.GetFullPath(“1.mp3”),0,0,0);

但抛出此异常:'Un4seen.Bass.Bass'的类型初始值设定项引发异常。

1 个答案:

答案 0 :(得分:1)

将Bass.dll添加到您的bin文件夹。