fatih
fatih

Reputation: 73

c# - BASS.Net create a spectrogram at once (not playing the music file)

This code I found here creates a spectogram of a given file but it keeps me waiting while it is playing and drawing the spectrogram.

I need to modify this code to create the spectrogram at once, without playing the file.

Thanks in advance.

public partial class Form1 : Form
{
    private int _handle;
    private int _pos;
    private BASSTimer _timer;
    private Visuals _visuals;

    public Form1()
    {
        InitializeComponent();
    }

    private void timer_Tick(object sender, EventArgs e)
    {
        bool spectrum3DVoicePrint = _visuals.CreateSpectrum3DVoicePrint(_handle, pictureBox1.CreateGraphics(),
                                                                        pictureBox1.Bounds, Color.Cyan, Color.Green,
                                                                        _pos, false, true);
        _pos++;
        if (_pos >= pictureBox1.Width)
        {
            _pos = 0;
        }
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        string file = "..\\..\\mysong.mp3";
        if (Bass.BASS_Init(-1, 44100, BASSInit.BASS_DEVICE_DEFAULT, Handle))
        {
            _handle = Bass.BASS_StreamCreateFile(file, 0, 0, BASSFlag.BASS_DEFAULT);

            if (Bass.BASS_ChannelPlay(_handle, false))
            {
                _visuals = new Visuals();
                _timer = new BASSTimer((int) (1.0d/10*1000));
                _timer.Tick += timer_Tick;
                _timer.Start();
            }
        }
    }
}

Upvotes: 1

Views: 2200

Answers (1)

Alexander
Alexander

Reputation: 121

Here's how I solved my problem. The idea is that you should not listen to the whole record, you can move the audio cursor and evaluate the spectrum at certain points.

    private Bitmap DrawSpectrogram(string fileName, int height, int stepsPerSecond)
    {
        Bass.BASS_Init(-1, 44100, BASSInit.BASS_DEVICE_DEFAULT, Handle);
        int channel = Bass.BASS_StreamCreateFile(fileName, 0, 0, BASSFlag.BASS_DEFAULT);

        long len = Bass.BASS_ChannelGetLength(channel, BASSMode.BASS_POS_BYTES); // the length in bytes
        double time = Bass.BASS_ChannelBytes2Seconds(channel, len); // the length in seconds

        int steps = (int)Math.Floor(stepsPerSecond * time);

        Bitmap result = new Bitmap(steps, height);
        Graphics g = Graphics.FromImage(result);

        Visuals visuals = new Visuals();


        Bass.BASS_ChannelPlay(channel, false);

        for (int i = 0; i < steps; i++)
        {
            Bass.BASS_ChannelSetPosition(channel, 1.0 * i / stepsPerSecond);
            visuals.CreateSpectrum3DVoicePrint(channel, g, new Rectangle(0, 0, result.Width, result.Height), Color.Black, Color.White, i, true, false);
        }

        Bass.BASS_ChannelStop(channel);

        Bass.BASS_Stop();
        Bass.BASS_Free();

        return result;
    }

Upvotes: 1

Related Questions