Author Topic: Direct bass : Vb.net (vb2008, vb2010, vb6, vc#, vc++, devC++, delphi, AutoIt)  (Read 179437 times)

sak2005

  • Posts: 972
Tip: SetVideoWindow in the mciSendString ::)

Example:
Code: [Select]
Public Class Form1
    Public Declare Auto Function mciSendString Lib "winmm.dll" (ByVal pCommand As String, ByVal strBuffer As System.Text.StringBuilder, ByVal bufferSize As Integer, ByVal hWndCallback As IntPtr) As Integer
    Public fDlg As New System.Windows.Forms.OpenFileDialog
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
       If fDlg.ShowDialog = Windows.Forms.DialogResult.OK Then
            Dim OpenCommand As String = String.Concat("open """, fDlg.FileName, """ type mpegvideo alias av parent ", Me.Handle, " style child")
            mciSendString(OpenCommand, Nothing, 0, IntPtr.Zero)
            Form1_LocationAndSizeChanged(sender, e)
            Dim PlayCommand As String = "play av"
            mciSendString(PlayCommand, Nothing, 0, IntPtr.Zero)
        End If
    End Sub
    Private Sub Form1_LocationAndSizeChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.LocationChanged, MyBase.SizeChanged
    Dim SetWindowCommand As String = String.Concat("put av destination at 0 0 ", Me.Width, " ", Me.Height)     
'OR
'Dim SetWindowCommand As String = String.Concat("put av window at 0 0 ", Me.Width, " ", Me.Height)
        mciSendString(SetWindowCommand, Nothing, 0, IntPtr.Zero)
    End Sub
End Class
« Last Edit: 14 Jul '17 - 01:38 by sak2005 »

sak2005

  • Posts: 972
Tip: VC++ VuMeter Function in the mciSound ;D

For parameters , Using by ref is % for progressBar.Value

Example:
Code: [Select]
viod VuMeter(int %vuLeft, int %vuRight )
{
    mciSendString("status capture level", buffer, buffer->Capacity, IntPtr::Zero);
    vuLeft = int.Parse(buffer->ToString()) & 65535;
    vuRight = (int.Parse(buffer->ToString()) >>16) & 65535;
    return;
}

sak2005

  • Posts: 972
Tip: Convert volume max value 1000 to max value 100 ::)

Example:
Code: [Select]
Public Sub Volume(ByVal vol As Integer)
    mciSendString("setaudio sound volume to " & ((1000/100)*vol).ToString(), Nothing, 0, IntPtr.Zero)
End Sub
« Last Edit: 28 Aug '17 - 01:24 by sak2005 »

sak2005

  • Posts: 972
Tip: Convert Balance max value 1000 to max value 100 ::)

Example:
Code: [Select]
Public Sub Balance(ByVal bal As Integer)
    If (bal > 0) Then
       mciSendString("setaudio sound left volume to " & ((100 - bal) *10).ToString(), Nothing, 0, IntPtr.Zero)
    End If             
    If (bal < 0) Then
        mciSendString("setaudio sound right volume to " & ((100 + bal) *10).ToString(), Nothing, 0, IntPtr.Zero)
    End If
End Sub
« Last Edit: 28 Aug '17 - 01:24 by sak2005 »

sak2005

  • Posts: 972
Tip: Info value Volume ::)

Example:
Code: [Select]
If TrackBar1.Value = 0 Then
    Label1.Text = "min"
ElseIf TrackBar1.Value = 50 Then
   Label1.Text = "center"
ElseIf TrackBar1.Value = 100 Then
   Label1.Text = "max"
Else
   Label1.Text = TrackBar1.Value
End If

sak2005

  • Posts: 972
Tip: Info value Balance ::)

Example:
Code: [Select]
If TrackBar2.Value = -100 Then
    Label2.Text = "left"
ElseIf TrackBar2.Value = 0 Then
   Label2.Text = "center"
ElseIf TrackBar2.Value = 100 Then
   Label2.Text = "right"
Else
   Label2.Text = TrackBar2.Value
End If

sak2005

  • Posts: 972
Tip: ReCodes, Learn more about with MS DShow Player ::)

This's converting max value Volume from 4000 to 100, For Volume control and Balance control.

Download: New! DShowLib-2005.dll , Modify add Class dshow control component. Clickhere

Example:
Code: [Select]
private void trackBar1_Scroll(object sender, EventArgs e)
        {
            dShow1.Balance((-4000 / -100) * trackBar1.Value);
            toolTip1.SetToolTip(trackBar1, ((-4000 / -100) * trackBar1.Value).ToString());
        }
       
        private void trackBar2_Scroll(object sender, EventArgs e)
        {
            dShow1.Volume((-4000 / -100) * trackBar2.Value);
            toolTip1.SetToolTip(trackBar2, ((-4000/-100) * trackBar2.Value).ToString());
        }
« Last Edit: 20 Jul '17 - 01:33 by sak2005 »

sak2005

  • Posts: 972
Tip: SetAttributes Volume ::) For mciSendString is maximum volume = 1000

Attributes maximum volume to max value 10 and max value 100

Support VolumeControl and BalanceControl

Code: [Select]
public int SetAttributes(int volValue, int maxValue)
{
    int _value = 0;
    if (maxValue==10)
    {
        _value = (1000 / 100) * volValue * 10;
        volValue = _value;
    }
    else if (maxValue==100)
    {
        _value = (1000 / 100) * volValue;
        volValue = _value;
    }
    else
    {
        if (maxValue==1000)
        {
            _value = (1000 / 1000) * volValue;
            volValue = _value;
        }
    }
    return _value;
}

Example:
Code: [Select]
private void trackBar2_Scroll(object sender, EventArgs e)
{
    pl.Volume(pl.SetAttributes(trackBar2.Value , 100));
}

private void trackBar3_Scroll(object sender, EventArgs e)
{
    pl.Balance(pl.SetAttributes(trackBar3.Value, 100));
}
« Last Edit: 23 Jul '17 - 18:36 by sak2005 »

sak2005

  • Posts: 972
Tip: VLC Player, Without VLC ActiveX ::)

Must add files is libvlc.dll, libvlccore.dll and plugins folder to the debug folder.

Example: Basic VLC
Code: [Select]
using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace WindowsFormsApplication2
{
    public partial class Form1 : Form
    {
        #region core
        [DllImport("libvlc")]
        private static extern IntPtr libvlc_new(int argc, string[] argv, ref libvlc_exception_t ex);
        [DllImport("libvlc.dll")]
        private static extern void libvlc_release(IntPtr instance);
        #endregion

        #region media
        [DllImport("libvlc")]
        private static extern IntPtr libvlc_media_new(IntPtr p_instance, string psz_mrl, ref libvlc_exception_t p_e);
        [DllImport("libvlc")]
        private static extern void libvlc_media_release(IntPtr p_meta_desc);
        #endregion

        #region player
        [DllImport("libvlc")]
        private static extern IntPtr libvlc_media_player_new_from_media(IntPtr media, ref libvlc_exception_t ex);
        [DllImport("libvlc")]
        private static extern void libvlc_media_player_release(IntPtr player);
        [DllImport("libvlc")]
        private static extern void libvlc_media_player_set_drawable(IntPtr player, IntPtr drawable, ref libvlc_exception_t p_e);
        [DllImport("libvlc")]
        private static extern void libvlc_media_player_play(IntPtr player, ref libvlc_exception_t ex);
        [DllImport("libvlc")]
        private static extern void libvlc_media_player_pause(IntPtr player, ref libvlc_exception_t ex);
        [DllImport("libvlc")]
        private static extern void libvlc_media_player_stop(IntPtr player, ref libvlc_exception_t ex);
        [DllImport("libvlc")]
        private static extern PlayerState libvlc_media_player_get_state(IntPtr player, ref libvlc_exception_t ex);
        #endregion

        #region exception
        [DllImport("libvlc")]
        public static extern void libvlc_exception_init(ref libvlc_exception_t p_exception);
        [DllImport("libvlc")]
        public static extern int libvlc_exception_raised(ref libvlc_exception_t p_exception);
        [DllImport("libvlc")]
        public static extern string libvlc_exception_get_message(ref libvlc_exception_t p_exception);
        #endregion

        #region constructors
        OpenFileDialog fDlg;
        Timer time;
        public libvlc_exception_t ex;
        public IntPtr instant;
        public IntPtr media;
        public IntPtr player;
        public string file;
        public Form1(): base()
        {
            this.StartPosition = FormStartPosition.CenterScreen;
            this.MaximizeBox = false;
            this.AutoSizeMode = AutoSizeMode.GrowAndShrink;
            InitializeComponent();
            panel1.BackColor = System.Drawing.Color.Black;
            time = new Timer();
            fDlg = new OpenFileDialog();
            ex = new libvlc_exception_t();
            instant = IntPtr.Zero;
            media = IntPtr.Zero;
            player = IntPtr.Zero;
            file = string.Empty;
            time.Tick += new EventHandler(time_Tick);
        }
        #endregion

        #region methods
        public void VlcInit()
        {
            //Loading plugin dlls in the plugins folder.
            string[] args = new string[] { "-I", "dummy", "--ignore-config", "--plugin-path", "--vout-filter=deinterlace", "--deinterlace-mode=blend" };
            instant = libvlc_new(args.Length, args, ref ex);
            Raise(ref ex);
            ex = new libvlc_exception_t();
            libvlc_exception_init(ref ex);
        }
        public void LoadMedia(string strFile, IntPtr Window)
        {
            //Streamfree.
            if (file != string.Empty) {Close(); }
            file = strFile;
            //Open media file.
            media = libvlc_media_new(instant, file, ref ex);
            Raise(ref ex);
            player = libvlc_media_player_new_from_media(media, ref ex);
            Raise(ref ex);
            libvlc_media_release(media);
            //Set VideoWindow. Note: If mouse doubleClick to fullscreen.
            libvlc_media_player_set_drawable(player, Window, ref ex);
            Raise(ref ex);
        }
        public void Play()
        {
            if (media == IntPtr.Zero && player == IntPtr.Zero) { return; }
            libvlc_media_player_play(player, ref ex);
            Raise(ref ex);
        }
        public void Pause()
        {
            if (media == IntPtr.Zero && player == IntPtr.Zero) { return; }
            libvlc_media_player_pause(player, ref ex);
            Raise(ref ex);
        }
        public void Stop()
        {
            if (media == IntPtr.Zero && player == IntPtr.Zero) { return; }
            libvlc_media_player_stop(player, ref ex);
            Raise(ref ex);
        }
        public void Close()
        {
            if (media == IntPtr.Zero && player == IntPtr.Zero) { return; }
            try
            { libvlc_media_player_release(player); }
            catch
            { libvlc_media_release(media); }
        }
        public PlayerState State
        {
            get
            {
                return libvlc_media_player_get_state(player, ref ex);
                Raise(ref ex);
            }
        }
        public void Raise(ref libvlc_exception_t ex)
        {
            if (libvlc_exception_raised(ref ex) != 0)
            {
                MessageBox.Show(libvlc_exception_get_message(ref ex));
            }
        }
        #endregion

        private void Form1_Load(object sender, EventArgs e)
        {
            VlcInit();
        }
        private void btnLoad_Click(object sender, EventArgs e)
        {
            if (fDlg.ShowDialog() == DialogResult.OK)
            {
                this.Text = fDlg.SafeFileName;
                LoadMedia(fDlg.FileName, panel1.Handle);
                btnPlay_Click(sender, e);
            }
        }
        private void btnPlay_Click(object sender, EventArgs e)
        {
           Play();
           time.Start();
        }
       
        private void btnPause_Click(object sender, EventArgs e)
        {
           Pause();
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
           Stop();
        }
        private void time_Tick(object sender, EventArgs e)
        {
            //Sync state stopped.
            if (State == PlayerState.stopped){btnStop_Click(sender, e);}
        }
    }

    #region struct exception
    [StructLayout(LayoutKind.Sequential, Pack = 1)]
    public struct libvlc_exception_t
    {
        public int b_raised;
        public int i_code;
        public string psz_message;
    }
    #endregion

    #region enum state
    public enum PlayerState : int
    {
        waiting,
        ready,
        opening,
        buffering,
        playing,
        paused,
        stopped,
        ended,
        error
    }
    #endregion
}


« Last Edit: 26 Jul '17 - 12:02 by sak2005 »

sak2005

  • Posts: 972
VLC Player.Net Sample: ;D
Code: [Select]
Public Class Form1
#Region "core"
    Private Declare Function libvlc_new Lib "libvlc" (ByVal argc As Integer, ByVal argv As String(), ByRef ex As libvlc_exception_t) As IntPtr
    Private Declare Sub libvlc_release Lib "libvlc" (ByVal instance As IntPtr)
#End Region

#Region "media"
    Private Declare Function libvlc_media_new Lib "libvlc" (ByVal player As IntPtr, ByVal file As String, ByRef ex As libvlc_exception_t) As IntPtr
    Private Declare Sub libvlc_media_release Lib "libvlc" (ByVal p_meta_desc As IntPtr)
#End Region

#Region "player"
    Private Declare Function libvlc_media_player_new_from_media Lib "libvlc" (ByVal media As IntPtr, ByRef ex As libvlc_exception_t) As IntPtr
    Private Declare Sub libvlc_media_player_release Lib "libvlc" (ByVal player As IntPtr)
    Private Declare Sub libvlc_media_player_set_drawable Lib "libvlc" (ByVal player As IntPtr, ByVal drawable As IntPtr, ByRef ex As libvlc_exception_t)
    Private Declare Sub libvlc_media_player_play Lib "libvlc" (ByVal player As IntPtr, ByRef ex As libvlc_exception_t)
    Private Declare Sub libvlc_media_player_pause Lib "libvlc" (ByVal player As IntPtr, ByRef ex As libvlc_exception_t)
    Private Declare Sub libvlc_media_player_stop Lib "libvlc" (ByVal player As IntPtr, ByRef ex As libvlc_exception_t)
    Private Declare Function libvlc_media_player_get_state Lib "libvlc" (ByVal player As IntPtr, ByRef ex As libvlc_exception_t) As PlayerState
#End Region

#Region "exceptions"
    Private Declare Sub libvlc_exception_init Lib "libvlc" (ByRef ex As libvlc_exception_t)
    Private Declare Function libvlc_exception_raised Lib "libvlc" (ByRef ex As libvlc_exception_t) As Integer
    Private Declare Function libvlc_exception_get_message Lib "libvlc" (ByRef ex As libvlc_exception_t) As String
#End Region

#Region "constructors"
    Private fDlg As OpenFileDialog
    Private time As System.Windows.Forms.Timer
    Public ex As libvlc_exception_t
    Public instant As IntPtr
    Public media As IntPtr
    Public player As IntPtr
    Public file As String
    Public Sub New()
        MyBase.New()
        Me.StartPosition = FormStartPosition.CenterScreen
        Me.MaximizeBox = False
        Me.AutoSizeMode = AutoSizeMode.GrowAndShrink
        InitializeComponent()
        Panel1.BackColor = System.Drawing.Color.Black
        time = New System.Windows.Forms.Timer
        fDlg = New OpenFileDialog
        ex = New libvlc_exception_t
        instant = IntPtr.Zero
        media = IntPtr.Zero
        player = IntPtr.Zero
        file = String.Empty
        AddHandler time.Tick, AddressOf time_Tick
    End Sub
#End Region

#Region "methods"
    Public Sub VlcInit()
        'Loading plugin dlls in the plugins folder.
        Dim args As String() = New String() {"-I", "dummy", "--ignore-config", "--plugin-path", "--vout-filter=deinterlace", "--deinterlace-mode=blend"}
        instant = libvlc_new(args.Length, args, ex)
        Raise(ex)
        ex = New libvlc_exception_t
        libvlc_exception_init(ex)
    End Sub
    Public Sub LoadMedia(ByVal strFile As String, ByVal Window As IntPtr)
        'Streamfree.
        If file <> String.Empty Then [Close]()
        file = strFile
        'Open media file.
        media = libvlc_media_new(instant, file, ex)
        Raise(ex)
        player = libvlc_media_player_new_from_media(media, ex)
        Raise(ex)
        libvlc_media_release(media)
        'Set VideoWindow. Note: If mouse doubleClick to fullscreen.
        libvlc_media_player_set_drawable(player, Window, ex)
        Raise(ex)
    End Sub
    Public Sub Play()
        If media = IntPtr.Zero AndAlso player = IntPtr.Zero Then Return
        libvlc_media_player_play(player, ex)
        Raise(ex)
    End Sub
    Public Sub Pause()
        If media = IntPtr.Zero AndAlso player = IntPtr.Zero Then Return
        libvlc_media_player_pause(player, ex)
        Raise(ex)
    End Sub
    Public Sub [Stop]()
        If media = IntPtr.Zero AndAlso player = IntPtr.Zero Then Return
        libvlc_media_player_stop(player, ex)
        Raise(ex)
    End Sub
    Public Shadows Sub [Close]()
        If media = IntPtr.Zero AndAlso player = IntPtr.Zero Then Return
        Try
            libvlc_media_player_release(player)
        Catch
            libvlc_media_release(media)
        End Try
    End Sub
    Public ReadOnly Property State() As PlayerState
        Get
            Return libvlc_media_player_get_state(player, ex)
            Raise(ex)
        End Get
    End Property
    Public Sub Raise(ByRef ex As libvlc_exception_t)
        If libvlc_exception_raised(ex) <> 0 Then
            MessageBox.Show(libvlc_exception_get_message(ex))
        End If
    End Sub
#End Region

    Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Load
        VlcInit()
    End Sub
    Private Sub btnLoad_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
        If fDlg.ShowDialog = Windows.Forms.DialogResult.OK Then
            Me.Text = fDlg.SafeFileName
            LoadMedia(fDlg.FileName, Panel1.Handle)
            btnPlay_Click(sender, e)
        End If
    End Sub
    Private Sub btnPlay_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button2.Click
        Play()
        time.Start()
    End Sub

    Private Sub btnPause_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button3.Click
        Pause()
    End Sub
    Private Sub btnStop_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button4.Click
        [Stop]()
    End Sub
    Private Sub time_Tick(ByVal sender As Object, ByVal e As EventArgs)
        'Sync state stopped.
        If State = PlayerState.stopped Then btnStop_Click(sender, e)
    End Sub
End Class

#Region "struct exceptions"
<Runtime.InteropServices.StructLayout(Runtime.InteropServices.LayoutKind.Sequential, CharSet:=Runtime.InteropServices.CharSet.Auto, Pack:=1)> _
Public Structure libvlc_exception_t
    Public b_raised As Integer
    Public i_code As Integer
    Public psz_message As String
End Structure
#End Region

#Region "enum state"
Public Enum PlayerState As Integer
    waiting
    ready
    opening
    buffering
    playing
    paused
    stopped
    ended
    [error]
End Enum
#End Region
« Last Edit: 26 Jul '17 - 15:21 by sak2005 »

sak2005

  • Posts: 972
Learn more about with Video DirectShow ::)

Created video project with Quartz.dll

Tip: If wanted playing type audio only, without of video format is hidden window.
       Must set Owner with new control.

Note: If playing song.wma not work, must config sound filters by checkbox support format WMA 



Example:
Code: [Select]
Imports QuartzTypeLib
Public Class Form1
    Public DShow As FilgraphManagerClass = Nothing
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
            If DShow IsNot Nothing Then Runtime.InteropServices.Marshal.ReleaseComObject(DShow)
            DShow = New FilgraphManagerClass
            DShow.RenderFile(OpenFileDialog1.FileName)
            Dim window As New Control
            Try
                DShow.Owner = window.Handle.ToInt32
            Catch ex As Exception
                Exit Try
            End Try
            DShow.Run()
        End If
    End Sub
End Class

« Last Edit: 28 Jul '17 - 12:23 by sak2005 »

sak2005

  • Posts: 972
Tip: How to using Video DShow Interface ::)

Example:
Code: [Select]
Imports QuartzTypeLib
Public Class Form1
    Public fg As FilgraphManager = Nothing
    Public mc As IMediaControl = Nothing
    Public vw As IVideoWindow = Nothing
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
            If fg IsNot Nothing Then Runtime.InteropServices.Marshal.ReleaseComObject(fg)
            fg = New FilgraphManager
            mc = DirectCast(fg, IMediaControl)
            vw = DirectCast(fg, IVideoWindow)
            mc.RenderFile(OpenFileDialog1.FileName)
            Dim window As New Control
            Try
                vw.Owner = window.Handle.ToInt32
            Catch ex As Exception
                Exit Try
            End Try
            mc.Run()
        End If
    End Sub
End Class

sak2005

  • Posts: 972
Tip: How to Video DShow ComImport ::)

DShowPlayer Short codes Sample:
Code: [Select]
Imports System.Runtime.InteropServices
Imports System.Security
Public Class Form1
    Private gb As IGraphBuilder = Nothing
    Private mc As IMediaControl = Nothing
    Private mp As IMediaPosition = Nothing
    Private vw As IVideoWindow = Nothing
    Private strFile As String = String.Empty
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
            If strFile <> String.Empty Then ReleaseGraph()
            strFile = OpenFileDialog1.FileName
            gb = DirectCast(New FilterGraph, IFilterGraph2)
            mc = DirectCast(gb, IMediaControl)
            mp = DirectCast(gb, IMediaPosition)
            vw = DirectCast(gb, IVideoWindow)
            mc.RenderFile(strFile)
            vw.put_Owner(Panel1.Handle)
            vw.put_WindowStyle(WindowStyle.Child)
            vw.SetWindowPosition(0, 0, Panel1.Width, Panel1.Height)
            Dim len As Double
            mp.get_Duration(len)
            Label3.Text = TimeSpan.FromSeconds(len).ToString.Substring(3, 5)
            TrackBar1.Maximum = CInt(len)
            mc.Run()
        End If
    End Sub
    Private Sub TrackBar1_Scroll(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TrackBar1.Scroll
        mp.put_CurrentPosition(CDbl(TrackBar1.Value))
    End Sub
    Private Function ReleaseGraph() As Integer
        If gb IsNot Nothing Then
            If Runtime.InteropServices.Marshal.IsComObject(gb) Then
                Return Runtime.InteropServices.Marshal.ReleaseComObject(gb)
            End If
        End If
    End Function
    Protected Overrides Sub OnClosing(ByVal e As System.ComponentModel.CancelEventArgs)
        MyBase.OnClosing(e)
        If MsgBox("Do you want to exit?", MsgBoxStyle.Question Or MsgBoxStyle.YesNo, "") = MsgBoxResult.Yes Then
            ReleaseGraph()
            gb = Nothing
            e.Cancel = False
        Else
            e.Cancel = True
        End If
    End Sub
End Class
<ComImport(), _
    Guid("e436ebb3-524f-11ce-9f53-0020af0ba770")> _
   Public Class FilterGraph
    Inherits Object
End Class
<ComImport(), _
    SuppressUnmanagedCodeSecurity(), _
    Guid("56a868a9-0ad4-11ce-b03a-0020af0ba770"), _
    InterfaceType(ComInterfaceType.InterfaceIsIUnknown)> _
   Public Interface IGraphBuilder
End Interface
<ComImport(), _
    Guid("56a8689f-0ad4-11ce-b03a-0020af0ba770"), _
    SuppressUnmanagedCodeSecurity(), _
    InterfaceType(ComInterfaceType.InterfaceIsIUnknown)> _
   Public Interface IFilterGraph
#Region "IFilterGraph Methods"
#End Region
End Interface
<ComImport(), _
     InterfaceType(ComInterfaceType.InterfaceIsIUnknown), _
     Guid("36b73882-c2c8-11cf-8b46-00805f6cef60"), _
     SuppressUnmanagedCodeSecurity()> _
    Public Interface IFilterGraph2
End Interface
<ComImport(), _
     Guid("56a868b1-0ad4-11ce-b03a-0020af0ba770"), _
     InterfaceType(ComInterfaceType.InterfaceIsDual), _
     SuppressUnmanagedCodeSecurity()> _
    Public Interface IMediaControl
#Region "IMediaControl Methods"
    <PreserveSig()> _
    Function Run() As Integer
    <PreserveSig()> _
    Function Pause() As Integer
    <PreserveSig()> _
    Function [Stop]() As Integer
    <PreserveSig()> _
    Function GetState(ByVal msTimeout As Integer, ByRef pfs As FilterState) As Integer
    <PreserveSig()> _
    Function RenderFile(<MarshalAs(UnmanagedType.BStr)> ByVal strFilename As String) As Integer
    <PreserveSig()> _
    Function StopWhenReady() As Integer
#End Region
End Interface
<ComImport(), _
     InterfaceType(ComInterfaceType.InterfaceIsDual), _
     SuppressUnmanagedCodeSecurity(), _
     Guid("56a868b2-0ad4-11ce-b03a-0020af0ba770")> _
    Public Interface IMediaPosition
#Region "IMediaPosition Methods"
    <PreserveSig()> _
    Function get_Duration(ByRef pLength As Double) As Integer
    <PreserveSig()> _
    Function put_CurrentPosition(ByVal llTime As Double) As Integer
    <PreserveSig()> _
    Function get_CurrentPosition(ByRef pllTime As Double) As Integer
#End Region
End Interface
<ComImport(), _
     SuppressUnmanagedCodeSecurity(), _
     Guid("56a868b4-0ad4-11ce-b03a-0020af0ba770"), _
     InterfaceType(ComInterfaceType.InterfaceIsDual)> _
    Public Interface IVideoWindow
#Region "IVideoWindow Methods"
    <PreserveSig()> _
    Function put_Caption(<MarshalAs(UnmanagedType.BStr)> ByVal caption As String) As Integer
    <PreserveSig()> _
    Function get_Caption(<MarshalAs(UnmanagedType.BStr)> ByRef caption As String) As Integer
    <PreserveSig()> _
    Function put_WindowStyle(ByVal windowStyle As WindowStyle) As Integer
    <PreserveSig()> _
    Function get_WindowStyle(ByRef windowStyle As WindowStyle) As Integer
    <PreserveSig()> _
    Function put_WindowStyleEx(ByVal windowStyleEx As WindowStyleEx) As Integer
    <PreserveSig()> _
    Function get_WindowStyleEx(ByRef windowStyleEx As WindowStyleEx) As Integer
    <PreserveSig()> _
    Function put_AutoShow(ByVal autoShow As OABool) As Integer
    <PreserveSig()> _
    Function get_AutoShow(ByRef autoShow As OABool) As Integer
    <PreserveSig()> _
    Function put_WindowState(ByVal windowState As WindowState) As Integer
    <PreserveSig()> _
    Function get_WindowState(ByRef windowState As WindowState) As Integer
    <PreserveSig()> _
    Function put_BackgroundPalette(ByVal backgroundPalette As OABool) As Integer
    <PreserveSig()> _
    Function get_BackgroundPalette(ByRef backgroundPalette As OABool) As Integer
    <PreserveSig()> _
    Function put_Visible(ByVal visible As OABool) As Integer
    <PreserveSig()> _
    Function get_Visible(ByRef visible As OABool) As Integer
    <PreserveSig()> _
    Function put_Left(ByVal left As Integer) As Integer
    <PreserveSig()> _
    Function get_Left(ByRef left As Integer) As Integer
    <PreserveSig()> _
    Function put_Width(ByVal width As Integer) As Integer
    <PreserveSig()> _
    Function get_Width(ByRef width As Integer) As Integer
    <PreserveSig()> _
    Function put_Top(ByVal top As Integer) As Integer
    <PreserveSig()> _
    Function get_Top(ByRef top As Integer) As Integer
    <PreserveSig()> _
    Function put_Height(ByVal height As Integer) As Integer
    <PreserveSig()> _
    Function get_Height(ByRef height As Integer) As Integer
    <PreserveSig()> _
    Function put_Owner(ByVal owner As System.IntPtr) As Integer
    <PreserveSig()> _
    Function get_Owner(ByRef owner As System.IntPtr) As Integer
    <PreserveSig()> _
    Function put_MessageDrain(ByVal drain As System.IntPtr) As Integer
    <PreserveSig()> _
    Function get_MessageDrain(ByRef drain As System.IntPtr) As Integer
    <PreserveSig()> _
    Function get_BorderColor(ByRef color As Integer) As Integer
    <PreserveSig()> _
    Function put_BorderColor(ByVal color As Integer) As Integer
    <PreserveSig()> _
    Function get_FullScreenMode(ByRef fullScreenMode As OABool) As Integer
    <PreserveSig()> _
    Function put_FullScreenMode(ByVal fullScreenMode As OABool) As Integer
    <PreserveSig()> _
    Function SetWindowForeground(ByVal focus As OABool) As Integer
    <PreserveSig()> _
    Function NotifyOwnerMessage(ByVal hwnd As System.IntPtr, ByVal msg As Integer, ByVal wParam As System.IntPtr, ByVal lParam As System.IntPtr) As Integer
    <PreserveSig()> _
    Function SetWindowPosition(ByVal left As Integer, ByVal top As Integer, ByVal width As Integer, ByVal height As Integer) As Integer
#End Region
End Interface
Public Enum FilterState
#Region "FilterState Fields"
    Stopped = 0
    Paused = 1
    Running = 2
#End Region
End Enum
Public Enum OABool
#Region "OABool Fields"
    [False] = 0
    [True] = -1
#End Region
End Enum
Public Enum WindowState
#Region "WindowState Fields"
    Hide = 0
    Normal = 1
    ShowMinimized = 2
    ShowMaximized = 3
    ShowNoActivate = 4
    Show = 5
    Minimize = 6
    ShowMinNoActive = 7
    ShowNA = 8
    Restore = 9
    ShowDefault = 10
    ForceMinimize = 11
#End Region
End Enum
<Flags()> _
    Public Enum WindowStyle
#Region "WindowStyle Fields"
    Overlapped = 0
    Popup = -2147483648
    Child = 1073741824
    Minimize = 536870912
    Visible = 268435456
    Disabled = 134217728
    ClipSiblings = 67108864
    ClipChildren = 33554432
    Maximize = 16777216
    Caption = 12582912
    Border = 8388608
    DlgFrame = 4194304
    VScroll = 2097152
    HScroll = 1048576
    SysMenu = 524288
    ThickFrame = 262144
    Group = 131072
    TabStop = 65536
    MinimizeBox = 131072
    MaximizeBox = 65536
#End Region
End Enum
<Flags()> _
    Public Enum WindowStyleEx
#Region "WindowStyleEx Fields"
    DlgModalFrame = 1
    NoParentNotify = 4
    Topmost = 8
    AcceptFiles = 16
    Transparent = 32
    MDIChild = 64
    ToolWindow = 128
    WindowEdge = 256
    ClientEdge = 512
    ContextHelp = 1024
    Right = 4096
    Left = 0
    RTLReading = 8192
    LTRReading = 0
    LeftScrollBar = 16384
    RightScrollBar = 0
    ControlParent = 65536
    StaticEdge = 131072
    APPWindow = 262144
    Layered = 524288
    NoInheritLayout = 1048576
    LayoutRTL = 4194304
    Composited = 33554432
    NoActivate = 134217728
#End Region
End Enum

« Last Edit: 1 Aug '17 - 09:20 by sak2005 »

sak2005

  • Posts: 972
Tip: Set Resize Window On Pausing in the DShow Player ::)

If error then return -1 Else return 0

Example:
Code: [Select]
public int SetWindow(Control window)
{
      int result = -1;
      if (vw != null)
     {
          result =  vw.put_Owner(window.Handle);
          result = vw.put_WindowStyle(WindowStyle.Child);
          if(result==0)
          {
               result= 0;
          }
     }
     return result;
}

public int ResizeWindow(Control window)
{
     int result = -1;
     if (vw != null)
    {
         if (State() == 1) //If pausing.
         {
              SetWindow(window);
              Application.DoEvents();
         }
         result = vw.SetWindowPosition(0, 0, window.Width, window.Height);
         if(result==0)
         {
              result = 0;
         }
    }
    return result;
}

public int State()
{
     FilterState st;
     int result = -1;
     if (mc != null)
     {
          mc.GetState(0, out st);
          result = (int)st;
     }
     return result;
}
« Last Edit: 6 Aug '17 - 15:36 by sak2005 »

sak2005

  • Posts: 972
Tip: Convert Time LenPos in the DShow Player ::)

Example:
Code: [Select]
Public Overridable Function Bytes2Seconds(ByVal LenPos As Long) As Double
        Return CDbl(LenPos / 10000000)
    End Function

    Public Overridable Function Seconds2Bytes(ByVal LenPos As Double) As Long
        Return CLng(LenPos * 10000000)
    End Function
« Last Edit: 11 Aug '17 - 04:30 by sak2005 »

sak2005

  • Posts: 972
Tip: Table Fix TimeSpan ::)

SubString(0, 11) = hh:mm:ss.ms
SubString(0, 8 ) = hh:mm:ss
SubString(3, 5) = mm:ss

Example:
Code: [Select]
Duration.Text = TimeSpan.FromSeconds(Duration).ToString()SubString(3, 5)
Position.Text = TimeSpan.FromSeconds(CurrentPosition).ToString()SubString(3, 5)
« Last Edit: 11 Aug '17 - 04:44 by sak2005 »

sak2005

  • Posts: 972
Tip: Learn more about with Methods is DsRect , NormalizedRect and Rectangle

For sample, using PictureBox

Example: DsRect
Code: [Select]
Dim dsRect As New DsRect(0, 0, PictureBox1.Right,  PictureBox1.Bottom)

Example: NormalizedRect
Code: [Select]
Dim nr As New NormalizedRect(0, 0, PictureBox1.Right,  PictureBox1.Bottom)

Example:  Rectangle
Code: [Select]
Dim rect As Rectangle = PictureBox1.ClientRectangle

OR

Code: [Select]
Dim rect As New Rectangle(0, 0, PictureBox1.Right,  PictureBox1.Bottom)


sak2005

  • Posts: 972
Tip: Using DShowVMR9 Player ::)

1. Build Graph
2. Mix, Filter and  Add filter VMR
3. Config VMR and SetRenderingMode  Windowless
4. SetVideoPosition
5. SetVideoClippingWindow

Example:
Code: [Select]
Imports DirectShowLib 'References DirectShowLib-2005
Imports System.Runtime.InteropServices

Public Class Form1
    Private gb As IGraphBuilder = Nothing
    Private mc As IMediaControl = Nothing
    Private ms As IMediaSeeking = Nothing
    Private bf As IBaseFilter = Nothing
    Private vfc As IVMRFilterConfig9 = Nothing
    Private vwc As IVMRWindowlessControl9 = Nothing

    Private WithEvents Timer1 As New System.Windows.Forms.Timer
    Private fDlg As New OpenFileDialog
    Private sFile As String = String.Empty
    Private IsRepeat As Boolean = False

    Public Sub New()
        MyBase.New()
        InitializeComponent()
        PictureBox1.BackColor = Color.Black
        Button1.Text = "Load"
    End Sub

    Protected Overrides Sub DestroyHandle()
        Marshal.ReleaseComObject(gb)
        gb = Nothing
        MyBase.DestroyHandle()
    End Sub
     
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Select Case Button1.Text
            Case "Load"
                If fDlg.ShowDialog = Windows.Forms.DialogResult.OK Then
                    If sFile <> String.Empty Then Marshal.ReleaseComObject(gb)
                    sFile = fDlg.FileName
                    Dim desRect As DsRect
                    gb = DirectCast(New FilterGraph, IGraphBuilder)
                    mc = DirectCast(gb, IMediaControl)
                    ms = DirectCast(gb, IMediaSeeking)
                    bf = DirectCast(New VideoMixingRenderer9, IBaseFilter)
                    gb.AddFilter(bf, "Video")
                    vfc = DirectCast(bf, IVMRFilterConfig9)
                    vfc.SetRenderingMode(VMR9Mode.Windowless)
                    vwc = DirectCast(bf, IVMRWindowlessControl9)
                    desRect = New DsRect(0, 0, PictureBox1.Right, PictureBox1.Bottom)
                    vwc.SetVideoPosition(Nothing, desRect)
                    vwc.SetVideoClippingWindow(PictureBox1.Handle)
                    gb.RenderFile(sFile, Nothing)
                    Dim MaxPosition As Long
                    ms.GetDuration(MaxPosition)
                    TrackBar1.Maximum = CInt(MaxPosition / 10000000)
                    Label2.Text = TimeSpan.FromSeconds(CDbl(MaxPosition / 10000000)).ToString.Substring(3, 5)
                    Button1.Text = "Play"
                End If
            Case "Play"
                Timer1.Enabled = True
                mc.Run()
                Button1.Text = "Pause/Stop"
            Case "Stop"
                Dim pos As New DsLong(0)
                ms.SetPositions(pos, AMSeekingSeekingFlags.AbsolutePositioning, Nothing, AMSeekingSeekingFlags.NoPositioning)
                mc.Stop()
                TrackBar1.Value = TrackBar1.Minimum
                Button1.Text = "Load"
            Case "Load/Play"
                If MsgBox("Do you want to Load?", MsgBoxStyle.YesNo Or MsgBoxStyle.Question, "") = MsgBoxResult.Yes Then
                    Button1.Text = "Load"
                Else
                    Button1.Text = "Play"
                End If
            Case Else
                If MsgBox("Do you want to Paused?", MsgBoxStyle.YesNo Or MsgBoxStyle.Question, "") = MsgBoxResult.Yes Then
                    mc.Pause()
                    Button1.Text = "Play"
                Else
                    mc.Stop()
                    Button1.Text = "Load/Play"
                End If
                Exit Select
        End Select
    End Sub

    Private Sub TrackBar1_Scroll(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TrackBar1.Scroll
        Dim pStart As New DsLong(TrackBar1.Value * 10000000)
        Dim pStop As New DsLong(0)
        ms.SetPositions(pStart, AMSeekingSeekingFlags.AbsolutePositioning, pStop, AMSeekingSeekingFlags.NoPositioning)
    End Sub

    Private Sub Timer1_Tick(ByVal sender As Object, ByVal e As EventArgs) Handles Timer1.Tick
        Dim pCurrent As Long
        ms.GetCurrentPosition(pCurrent)
        If TrackBar1.Value < TrackBar1.Maximum Then
            TrackBar1.Value = pCurrent / 10000000
            Label1.Text = TimeSpan.FromSeconds(CDbl(pCurrent / 10000000)).ToString.Substring(3, 5)
        Else
            If IsRepeat = True Then
                Dim pos As New DsLong(0)
                ms.SetPositions(pos, AMSeekingSeekingFlags.AbsolutePositioning, Nothing, AMSeekingSeekingFlags.NoPositioning)
                TrackBar1.Value = TrackBar1.Minimum
            Else
                Dim pos As New DsLong(0)
                ms.SetPositions(pos, AMSeekingSeekingFlags.AbsolutePositioning, Nothing, AMSeekingSeekingFlags.NoPositioning)
                mc.Stop()
                TrackBar1.Value = TrackBar1.Minimum
                Button1.Text = "Play"
            End If
        End If
    End Sub

    Private Sub CheckBox1_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CheckBox1.CheckedChanged
        If CheckBox1.Checked Then
            IsRepeat = True
        Else
            IsRepeat = False
        End If
    End Sub
End Class

FreeDownload: dshow.dll V1.0 (trial version) Clickhere

Info:
- Added DShowClass
- Added Vumeter function

« Last Edit: 15 Aug '17 - 12:15 by sak2005 »

sak2005

  • Posts: 972
Tip: Using.. BassStreamCreateFileMemory and BassStreamCreateFileUnicode ::)

Example:
Code: [Select]
Public Class Form1

    Private Declare Auto Function BASS_Init Lib "bass" (ByVal device As Integer, ByVal freq As Integer, ByVal flags As Integer, ByVal win As IntPtr, ByVal clsid As IntPtr) As Boolean
    Private Declare Auto Function BASS_StreamFree Lib "bass" (ByVal handle As Integer) As Boolean
    Private Declare Auto Function BASS_StreamCreateFileMemory Lib "bass" Alias "BASS_StreamCreateFile" (ByVal mem As Boolean, ByVal strFile As System.IntPtr, ByVal offset As Long, ByVal length As Long, ByVal flags As Integer) As Integer
    Private Declare Auto Function BASS_StreamCreateFileUnicode Lib "bass" Alias "BASS_StreamCreateFile" (ByVal mem As Boolean, ByVal strFile As System.String, ByVal offset As Long, ByVal length As Long, ByVal flags As Integer) As Integer
    Private Declare Auto Function BASS_ChannelPlay Lib "bass" (ByVal handle As Integer, ByVal restart As Boolean) As Boolean

    Private chan As Integer

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        BASS_Init(-1, 44100, 0, Me.Handle, IntPtr.Zero) Then
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
            If CBool(chan) Then BASS_StreamFree(chan)
            chan = BASS_StreamCreateFile(String2Ptr(OpenFileDialog1.FileName), 0, 0, 0)
            BASS_ChannelPlay(chan, False)
        End If
    End Sub

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
            If CBool(chan) Then BASS_StreamFree(chan)
            chan = BASS_StreamCreateFile(OpenFileDialog1.FileName, 0, 0, 0)
            BASS_ChannelPlay(chan, False)
        End If
    End Sub

    Public Overridable Overloads Function BASS_StreamCreateFile(ByVal strFile As IntPtr, ByVal offset As Long, ByVal length As Long, ByVal flags As Integer) As Integer
        flags = flags Or 0 'if added unicode and mem = true, will not work.
        Return BASS_StreamCreateFileMemory(False, strFile, offset, length, flags)
    End Function

    Public Overridable Overloads Function BASS_StreamCreateFile(ByVal strFile As String, ByVal offset As Long, ByVal length As Long, ByVal flags As Integer) As Integer
        flags = flags Or -2147483648 'if not add unicode, will not work.
        Return BASS_StreamCreateFileUnicode(False, strFile, offset, length, flags)
    End Function

    Public Overridable Function String2Ptr(ByVal strFile As String) As IntPtr
        Return Runtime.InteropServices.Marshal.StringToHGlobalAnsi(strFile)
    End Function
End Class
« Last Edit: 15 Aug '17 - 23:56 by sak2005 »

sak2005

  • Posts: 972
Tip:Created Equalizer, Using.. DirectSound ::)

Must References Import Microsoft.DirectX and  Microsoft.DirectSound

Support WAV file only, If wanted play MP3, Must Decode or Encode convert .mp3 to .wav

Example:
Code: [Select]
Imports Microsoft.DirectX
Imports Microsoft.DirectX.DirectSound

Public Class MainForm
    Private dseq As DSoundEQ

    Public Sub New()
        MyBase.New()
        InitializeComponent()
        dseq = New DSoundEQ(Me.Handle)
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
            dseq.Open(OpenFileDialog1.FileName)
            dseq.SetFxEQ(5)
            UpdateParamsEQ(sender, e)
            Button2_Click(sender, e)
        End If
    End Sub

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        dseq.Play()
    End Sub

    Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
        dseq.Stop()
    End Sub

    Private Sub TrackBar1_Scroll(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TrackBar1.Scroll
        dseq.SetFxParamsEQ(0, 100, TrackBar1.Value)
    End Sub

    Private Sub TrackBar2_Scroll(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TrackBar2.Scroll
        dseq.SetFxParamsEQ(1, 500, TrackBar2.Value)
    End Sub

    Private Sub TrackBar3_Scroll(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TrackBar3.Scroll
        dseq.SetFxParamsEQ(2, 1000, TrackBar3.Value)
    End Sub

    Private Sub TrackBar4_Scroll(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TrackBar4.Scroll
        dseq.SetFxParamsEQ(3, 4000, TrackBar4.Value)
    End Sub

    Private Sub TrackBar5_Scroll(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TrackBar5.Scroll
        dseq.SetFxParamsEQ(4, 8000, TrackBar5.Value)
    End Sub

    Private Sub UpdateParamsEQ(ByVal sender As Object, ByVal e As EventArgs)
        TrackBar1_Scroll(sender, e)
        TrackBar2_Scroll(sender, e)
        TrackBar3_Scroll(sender, e)
        TrackBar4_Scroll(sender, e)
        TrackBar5_Scroll(sender, e)
    End Sub
End Class

Public Class DSoundEQ
    Inherits Object

    Private devList As DevicesCollection
    Private dev As Device
    Private bd As BufferDescription
    Private sb As SecondaryBuffer
    Private fx As EffectDescription()
    Private sFile As String

    Public Sub New(ByVal owner As IntPtr)
        Me.devList = New DevicesCollection()
        Me.dev = New Device(devList(0).DriverGuid)
        dev.SetCooperativeLevel(owner, CooperativeLevel.Priority)
        Me.bd = New BufferDescription()
        bd.Flags = BufferDescriptionFlags.ControlVolume Or BufferDescriptionFlags.ControlFrequency Or BufferDescriptionFlags.ControlPan Or BufferDescriptionFlags.ControlEffects
        Me.sFile = String.Empty
    End Sub

    Protected Overrides Sub Finalize()
        Me.dev.Dispose()
        Me.bd.Dispose()
        MyBase.Finalize()
    End Sub

    Public Overridable Sub Open(ByVal strFile As String)
        If sFile <> String.Empty Then
            [Stop]()
        End If
        sFile = strFile
        sb = New SecondaryBuffer(sFile, bd, dev)
    End Sub

    Public Overridable Sub Play()
        If sb IsNot Nothing Then
            sb.Play(0, BufferPlayFlags.Default)
        End If
    End Sub

    Public Overridable Sub [Stop]()
        If sb IsNot Nothing Then
            sb.SetCurrentPosition(0)
            sb.Stop()
        End If
    End Sub

    Public Overridable Sub SetFxEQ(ByVal bandCount As Integer)
        Try
            fx = New EffectDescription(bandCount) {}
            For i As Integer = 0 To bandCount
                fx(i).GuidEffectClass = DSoundHelper.StandardParamEqGuid
            Next i
            sb.SetEffects(fx)
            Dim eqEffect As ParamEqEffect = CType(sb.GetEffects(bandCount), ParamEqEffect)
            Dim eqParams As EffectsParamEq = eqEffect.AllParameters
            eqParams.Bandwidth = ParamEqEffect.BandwidthMax
            eqParams.Center = ParamEqEffect.CenterMin
            eqParams.Gain = ParamEqEffect.GainMin
            eqEffect.AllParameters = eqParams
        Catch ex As Exception
            Return
        End Try
    End Sub

    Public Overridable Sub SetFxParamsEQ(ByVal bandIndex As Integer, ByVal center As Integer, ByVal gain As Integer)
        Try
            fx(bandIndex) = New EffectDescription()
            Dim eqEffect As ParamEqEffect = CType(sb.GetEffects(bandIndex), ParamEqEffect)
            Dim eqParams As EffectsParamEq = eqEffect.AllParameters
            eqParams.Bandwidth = ParamEqEffect.BandwidthMax
            eqParams.Center = CSng(center)
            eqParams.Gain = CSng(gain)
            eqEffect.AllParameters = eqParams
        Catch ex As Exception
            Return
        End Try
    End Sub
End Class
« Last Edit: 25 Aug '17 - 01:32 by sak2005 »

sak2005

  • Posts: 972
Tip: Playing file.wav and create effect sound is equalizer with DirectSound SDK ::)

Sample code: EqClass.vb
Code: [Select]
Option Explicit Off
Option Strict On
Imports System.Windows.Forms
Imports Microsoft.DirectX
Imports Microsoft.DirectX.DirectSound
Public Class EqClass
    Inherits Object
    Private PosTime As System.Windows.Forms.Timer
    Private dev As Device
    Private bfd As BufferDescription
    Private spk As Speakers
    Private soundBuffer As SecondaryBuffer
    Private pos As Double
    Public Sub New()
        MyBase.New()
        PosTime = New System.Windows.Forms.Timer
        PosTime.Interval = 50
        AddHandler PosTime.Tick, New EventHandler(AddressOf PosTime_Tick)
    End Sub
    Public Overridable Sub InitSoundBuffer(ByVal hwnd As IntPtr)
        dev = New Device
        bfd = New BufferDescription
        spk = New Speakers
        bfd.ControlPan = True
        bfd.ControlVolume = True
        bfd.ControlFrequency = True
        bfd.ControlEffects = True
        spk.Mono = False
        spk.Headphone = False
        spk.Stereo = True
        spk.Quad = False
        spk.SevenPointOne = False
        spk.SevenPointOne = False
        spk.Surround = False
        dev.SpeakerConfig = spk
        dev.SetCooperativeLevel(hwnd, CooperativeLevel.Priority)
    End Sub
    Public Overridable Sub Load(ByVal strFile As String)
        soundBuffer = New SecondaryBuffer(strFile, bfd, dev)
    End Sub
    Public Overridable Sub Play(Optional ByVal repeat As Boolean = False)
        If soundBuffer IsNot Nothing Then
            If Not PosTime.Enabled Then PosTime.Start()
            If repeat Then
                soundBuffer.Play(0, BufferPlayFlags.Looping)
            Else
                soundBuffer.Play(0, BufferPlayFlags.Default)
            End If
        End If
    End Sub
    Public Overridable Sub Pause()
        If soundBuffer IsNot Nothing Then
            soundBuffer.Stop()
        End If
    End Sub
    Public Overridable Sub [Stop]()
        If soundBuffer IsNot Nothing Then
            SetPosition(0.0)
            soundBuffer.Stop()
        End If
    End Sub
    Public Overridable Function State() As Integer
        If soundBuffer IsNot Nothing Then
            If soundBuffer.Status.Playing Then
                Return 1
            End If
            If CurrentPosition < 1 Then
                Return 0
            Else
                Return 2
            End If
        End If
    End Function
    Public Overridable ReadOnly Property Status() As String
        Get
            Dim ret As String = String.Empty
            Select Case State()
                Case 1
                    ret = "Playing"
                Case 2
                    ret = "Paused"
                Case Else
                    ret = "Stopped"
            End Select
            Return ret
        End Get
    End Property
    Public Overridable Function GetLength() As Long
        Return CLng(soundBuffer.Caps.BufferBytes)
    End Function
    Public Overridable Function GetPosition() As Long
        Return CLng(soundBuffer.PlayPosition)
    End Function
    Public Overridable Function Bytes2Seconds(ByVal lenpos As Long) As Double
        Return CDbl(lenpos / soundBuffer.Format.AverageBytesPerSecond)
    End Function
    Public Overridable Function Seconds2Bytes(ByVal lenpos As Double) As Long
        Return CLng(lenpos * soundBuffer.Format.AverageBytesPerSecond)
    End Function
    Public Overridable ReadOnly Property Duration() As Double
        Get
            Return Bytes2Seconds(soundBuffer.Caps.BufferBytes)
        End Get
    End Property
    Public Overridable ReadOnly Property MaxPosition() As Double
        Get
            Return Duration()
        End Get
    End Property
    Public Overridable Sub SetPosition(ByVal pos As Double)
        Dim pp As Double = CDbl(soundBuffer.PlayPosition)
        pp = pos
        soundBuffer.SetCurrentPosition(CInt(Seconds2Bytes(pos)))
    End Sub
    Public Overridable Property CurrentPosition() As Double
        Get
            If soundBuffer IsNot Nothing Then
                pos = CDbl(soundBuffer.PlayPosition)
                Return Bytes2Seconds(CLng(pos))
            End If
        End Get
        Set(ByVal value As Double)
            pos = value
            soundBuffer.SetCurrentPosition(CInt(Seconds2Bytes(pos)))
        End Set
    End Property
    Public Overridable Sub SetFxEq(ByVal bandCount As Integer)
        Dim fx As EffectDescription() = New EffectDescription(bandCount) {}
        Dim i As Integer
        For i = 0 To bandCount
            fx(i).GuidEffectClass = DSoundHelper.StandardParamEqGuid
        Next i
        soundBuffer.SetEffects(fx)
        Dim eqEffect As ParamEqEffect = CType(soundBuffer.GetEffects(bandCount), ParamEqEffect)
        Dim eqParams As EffectsParamEq = eqEffect.AllParameters
        eqParams.Bandwidth = ParamEqEffect.BandwidthMax
        eqParams.Center = ParamEqEffect.CenterMin
        eqParams.Gain = ParamEqEffect.GainMin
        eqEffect.AllParameters = eqParams
    End Sub
    Public Overridable Sub SetFxEqParaMeter(ByVal bandIndex As Integer, ByVal center As Integer, ByVal gain As Integer)
        Dim eqEffect As ParamEqEffect = CType(soundBuffer.GetEffects(bandIndex), ParamEqEffect)
        Dim eqParams As EffectsParamEq = eqEffect.AllParameters
        eqParams.Bandwidth = ParamEqEffect.BandwidthMax
        eqParams.Center = CSng(center)
        eqParams.Gain = CSng(gain)
        eqEffect.AllParameters = eqParams
    End Sub
    Private Sub PosTime_Tick(ByVal sender As Object, ByVal e As EventArgs)
        RaiseEvent PositionChanged(Me, New EventArgs)
    End Sub
    Public Event PositionChanged As System.EventHandler
End Class
« Last Edit: 28 Aug '17 - 23:41 by sak2005 »

sak2005

  • Posts: 972
Example: Form Application
Code: [Select]
Imports FFmpegConvert
Imports System.IO
Imports Microsoft.DirectX
Imports Microsoft.DirectX.DirectSound
Public Class Form1
    Private fmc As New FFmpegClass
    Private mpl As New MciClass
    Private deq As New EqClass
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        deq.InitSoundBuffer(Me.Handle)
    End Sub
    Public Sub New()
        MyBase.New()
        InitializeComponent()
        OpenFileDialog1.FileName = String.Empty
        OpenFileDialog1.Filter = "MP4|*.mp4|WAV|*.wav|WMA|*.wma|MP3|*.mp3|MKV|*.mkv|WMV|*.wmv|AVI|*.avi|ALL|*.*"
        SaveFileDialog1.FileName = String.Empty
        SaveFileDialog1.Filter = "MP3|*.mp3|WAV|*.wav|WMA|*.wma|MP4|*.mp4|MKV|*.mkv|WMV|*.wmv|AVI|*.avi|ALL|*.*"
        AddHandler fmc.DoWorkEventChanged, AddressOf fmc_DoWorkEventChanged
        AddHandler fmc.CompleteEventChanged, AddressOf fmc_CompleteEventChanged
        AddHandler mpl.PositionChanged, AddressOf mpl_PositionChanged
        AddHandler deq.PositionChanged, AddressOf deq_PositionChanged
    End Sub
    Private Sub deq_PositionChanged(ByVal sender As Object, ByVal e As EventArgs)
        Label15.Text = TimeSpan.FromSeconds(deq.CurrentPosition).ToString.Substring(0, 8)
        TrackBar4.Value = CInt(deq.CurrentPosition)
        Label17.Text = "Status: " & deq.Status
    End Sub
    Private Sub mpl_PositionChanged(ByVal sender As Object, ByVal e As EventArgs)
        If Label3.Text.Length > 12 Then
            Label3.Text = InputInfo
        Else
            Label4.Text = OutputInfo
        End If
        TrackBar1.Value = CInt(mpl.CurrentPosition)
        ProgressBar1.Value = mpl.LevelLeft
        ProgressBar2.Value = mpl.LevelRight
    End Sub
    Private Sub fmc_DoWorkEventChanged(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs)
        fmc.Convert(TextBox1.Text, TextBox2.Text, lblProc)
    End Sub
    Private Sub fmc_CompleteEventChanged(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs)
        btnStart.Enabled = True
        Label3.Text = "Input Info:"
        mpl.Load(TextBox2.Text)
        TrackBar1.Maximum = CInt(mpl.MaxPosition)
        Label4.Text = OutputInfo
    End Sub
    Private Sub btnBrowse_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBrowse.Click
        If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
            TextBox1.Text = OpenFileDialog1.FileName
            Me.Refresh()
            mpl.Load(TextBox1.Text)
            TrackBar1.Maximum = CInt(mpl.MaxPosition)
            Label3.Text = InputInfo
            If TextBox2.Text.Length > 12 Then
                Label4.Text = "Output Info:"
            End If
        End If
    End Sub
    Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click
        SaveFileDialog1.FileName = IO.Path.GetFileNameWithoutExtension(TextBox1.Text)
        If SaveFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
            TextBox2.Text = SaveFileDialog1.FileName
        End If
    End Sub
    Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
        If TextBox1.Text = String.Empty Then
            MsgBox("Before Browse file to convert")
        ElseIf TextBox2.Text = String.Empty Then
            MsgBox("Before Save file to convert")
        Else
            fmc.StartConvert()
            btnStart.Enabled = False
        End If
    End Sub
    Private Sub btnCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancel.Click
        If TextBox1.Text = String.Empty Then
            MsgBox("Before Browse file to convert")
        ElseIf TextBox2.Text = String.Empty Then
            MsgBox("Before Save file to convert")
        Else
            fmc.CancelConvert()
        End If
    End Sub
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Dim fdlg As New OpenFileDialog
        fdlg.FileName = String.Empty
        If fdlg.ShowDialog = Windows.Forms.DialogResult.OK Then
            mpl.Load(fdlg.FileName)
            TrackBar1.Maximum = CInt(mpl.MaxPosition)
            Button2_Click(sender, e)
        End If
    End Sub
    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        mpl.Play(True)
        TrackBar2_Scroll(sender, e)
        TrackBar3_Scroll(sender, e)
    End Sub
    Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
        mpl.Pause(True)
    End Sub
    Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
        mpl.Stop()
    End Sub
    Private Sub TrackBar1_Scroll(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TrackBar1.Scroll
        mpl.SetPosition(CDbl(TrackBar1.Value))
    End Sub
    Private Sub TrackBar2_Scroll(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TrackBar2.Scroll, TrackBar2.ValueChanged
        mpl.Volume(TrackBar2.Value)
    End Sub
    Private Sub TrackBar3_Scroll(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TrackBar3.Scroll, TrackBar3.ValueChanged
        mpl.Balance(TrackBar3.Value)
    End Sub
    Private Sub CheckBox1_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CheckBox1.CheckedChanged
        If CheckBox1.Checked Then
            mpl.Volume(0)
            mpl.Balance(0)
        Else
            mpl.Volume(TrackBar2.Value)
            mpl.Balance(TrackBar3.Value)
        End If
    End Sub
    Public Overridable ReadOnly Property InputInfo() As String
        Get
            Dim txt As String = String.Empty
            txt &= "Input Info: " & vbCrLf & _
            "FileName: " & Path.GetFileName(TextBox1.Text) & vbCrLf & _
            " Duration: " & TimeSpan.FromMilliseconds(mpl.Duration).ToString.Substring(0, 8) & vbCrLf & _
            "  Position: " & TimeSpan.FromMilliseconds(mpl.CurrentPosition).ToString.Substring(0, 8) & vbCrLf & _
            "    Status: " & mpl.Status
            Return txt
        End Get
    End Property
    Public Overridable ReadOnly Property OutputInfo() As String
        Get
            Dim txt As String = String.Empty
            txt &= "Output Info: " & vbCrLf & _
            "FileName: " & Path.GetFileName(TextBox2.Text) & vbCrLf & _
            " Duration: " & TimeSpan.FromMilliseconds(mpl.Duration).ToString.Substring(0, 8) & vbCrLf & _
            "  Position: " & TimeSpan.FromMilliseconds(mpl.CurrentPosition).ToString.Substring(0, 8) & vbCrLf & _
            "    Status: " & mpl.Status
            Return txt
        End Get
    End Property
    Private Sub Button1_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim fdlg As New OpenFileDialog
        fdlg.FileName = String.Empty
        fdlg.Filter = "wave file|*.wav"
        If fdlg.ShowDialog = Windows.Forms.DialogResult.OK Then
            Me.Refresh()
            deq.Load(fdlg.FileName)
            Label16.Text = TimeSpan.FromSeconds(deq.Duration).ToString.Substring(0, 8)
            TrackBar4.Maximum = CInt(deq.MaxPosition)
            deq.SetFxEq(9)
            UpdateParaMeterEQ(sender, e)
            Button5_Click(sender, e)
        End If
    End Sub
    Private Sub TrackBar4_Scroll(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TrackBar4.Scroll
        deq.CurrentPosition = TrackBar4.Value
    End Sub
    Private Sub Button5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button5.Click
        deq.Play(True)
    End Sub
    Private Sub Button7_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button7.Click
        deq.Pause()
    End Sub
    Private Sub Button6_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button6.Click
        deq.Stop()
    End Sub
    Private Sub tEQ0_Scroll(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tEQ0.Scroll, tEQ0.ValueChanged
        deq.SetFxEqParaMeter(0, 80, tEQ0.Value)
    End Sub
    Private Sub tEQ1_Scroll(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tEQ1.Scroll, tEQ1.ValueChanged
        deq.SetFxEqParaMeter(1, 160, tEQ1.Value)
    End Sub
    Private Sub tEQ2_Scroll(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tEQ2.Scroll, tEQ2.ValueChanged
        deq.SetFxEqParaMeter(2, 320, tEQ2.Value)
    End Sub
    Private Sub tEQ3_Scroll(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tEQ3.Scroll, tEQ3.ValueChanged
        deq.SetFxEqParaMeter(3, 640, tEQ3.Value)
    End Sub
    Private Sub tEQ4_Scroll(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tEQ4.Scroll, tEQ4.ValueChanged
        deq.SetFxEqParaMeter(4, 1000, tEQ4.Value)
    End Sub
    Private Sub tEQ5_Scroll(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tEQ5.Scroll, tEQ5.ValueChanged
        deq.SetFxEqParaMeter(5, 3000, tEQ5.Value)
    End Sub
    Private Sub tEQ6_Scroll(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tEQ6.Scroll, tEQ6.ValueChanged
        deq.SetFxEqParaMeter(6, 6000, tEQ6.Value)
    End Sub
    Private Sub tEQ7_Scroll(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tEQ7.Scroll, tEQ7.ValueChanged
        deq.SetFxEqParaMeter(7, 12000, tEQ7.Value)
    End Sub
    Private Sub tEQ8_Scroll(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tEQ8.Scroll, tEQ8.ValueChanged
        deq.SetFxEqParaMeter(8, 14000, tEQ8.Value)
    End Sub
    Private Sub tEQ9_Scroll(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tEQ9.Scroll, tEQ9.ValueChanged
        deq.SetFxEqParaMeter(9, 16000, tEQ9.Value)
    End Sub
    Public Overridable Sub UpdateParaMeterEQ(ByVal sender As Object, ByVal e As EventArgs)
        tEQ0_Scroll(sender, e)
        tEQ1_Scroll(sender, e)
        tEQ2_Scroll(sender, e)
        tEQ3_Scroll(sender, e)
        tEQ4_Scroll(sender, e)
        tEQ5_Scroll(sender, e)
        tEQ6_Scroll(sender, e)
        tEQ7_Scroll(sender, e)
        tEQ8_Scroll(sender, e)
        tEQ9_Scroll(sender, e)
    End Sub
End Class

« Last Edit: 29 Aug '17 - 00:02 by sak2005 »

sak2005

  • Posts: 972
FFmpeg Convert Class:
Code: [Select]
Option Explicit Off
Option Strict On
Imports System
Imports System.IO
Imports System.ComponentModel
Imports System.Windows.Forms
Imports System.Diagnostics
Public Class FFmpegClass
    Inherits Object
#Region "Constructors Fields"
    Private _BackgroundWorker As BackgroundWorker = Nothing
    Private _Process As Process = Nothing
    Private _Input As String
    Private _Options As String
    Private _Output As String
    Private _FileName As String
    Public Sub New()
        MyBase.New()
        If Not File.Exists(Path.Combine(Application.StartupPath, "ffmpeg.exe")) Then
            FileIO.FileSystem.WriteAllBytes(Path.Combine(Application.StartupPath, "ffmpeg.exe"), My.Resources.ffmpeg, True)
        End If
        Me._BackgroundWorker = New BackgroundWorker
        _BackgroundWorker.WorkerSupportsCancellation = True
        Me._Process = New Process
        Me._Input = String.Empty
        Me._Options = String.Empty
        Me._Output = String.Empty
        Me._FileName = String.Empty
        AddHandler _BackgroundWorker.DoWork, New System.ComponentModel.DoWorkEventHandler(AddressOf BackgroundWorker1_DoWork)
        AddHandler _BackgroundWorker.RunWorkerCompleted, New System.ComponentModel.RunWorkerCompletedEventHandler(AddressOf BackgroundWorker1_RunWorkerCompleted)
    End Sub
#End Region
    Protected Overrides Sub Finalize()
        Dim Proc As Process() = Process.GetProcessesByName("ffmpeg")
        For Each p As Process In Proc
            If p.ProcessName = "ffmpeg" Then
                _Process.Kill()
            End If
        Next p
        _Process = Nothing
        MyBase.Finalize()
    End Sub
#Region "FFmpeg Methods Fields"
    Public Overridable Overloads Sub Convert(ByVal Input As String, ByVal Output As String, ByVal Report As Control)
        Control.CheckForIllegalCrossThreadCalls = False
        _Input = Input
        _Output = Output
        _Process.StartInfo.FileName = "ffmpeg.exe"
        _Process.StartInfo.Arguments = "-i """ & _Input & """ """ & _Output
        _Process.StartInfo.UseShellExecute = False
        _Process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden
        _Process.StartInfo.RedirectStandardError = True
        _Process.StartInfo.CreateNoWindow = True
        _Process.Start()
        Do
            If _BackgroundWorker.CancellationPending Then
                _Process.Kill()
                Exit Do
            Else
                Report.Text = "Converting: " & _Process.StandardError.ReadLine
            End If
            Application.DoEvents()
        Loop Until _Process.HasExited Or _Process.StandardError.EndOfStream
        Report.Text = String.Empty
    End Sub
    Public Overridable Overloads Sub Convert(ByVal Input As String, ByVal Output As String)
        Control.CheckForIllegalCrossThreadCalls = False
        _Input = Input
        _Output = Output
        _Process.StartInfo.FileName = "ffmpeg.exe"
        _Process.StartInfo.Arguments = "-i """ & _Input & """ """ & _Output
        _Process.StartInfo.UseShellExecute = False
        _Process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden
        _Process.StartInfo.RedirectStandardError = False
        _Process.StartInfo.CreateNoWindow = True
        _Process.Start()
        Do
            If _BackgroundWorker.CancellationPending Then
                _Process.Kill()
                Exit Do
            End If
            Application.DoEvents()
        Loop Until _Process.HasExited
    End Sub
    Public Overridable Sub StartConvert()
        _BackgroundWorker.RunWorkerAsync()
    End Sub
    Public Overridable Sub CancelConvert()
        _BackgroundWorker.CancelAsync()
    End Sub
    Public Overridable Sub Close()
        _Process.Kill()
    End Sub
#End Region
#Region "FFmpeg Properties Fields"
    Public Property Input() As String
        Get
            Return _Input
        End Get
        Set(ByVal value As String)
            _Input = value
        End Set
    End Property
    Public Property Output() As String
        Get
            Return _Output
        End Get
        Set(ByVal value As String)
            _Output = value
        End Set
    End Property
    Public Property Options() As String
        Get
            Return _Options
        End Get
        Set(ByVal value As String)
            _Options = value
        End Set
    End Property
    Public Property Filename() As String
        Get
            Return _FileName
        End Get
        Set(ByVal value As String)
            _FileName = value
        End Set
    End Property
#End Region
#Region "FFmpeg Events Fields"
    Public Sub BackgroundWorker1_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs)
        RaiseEvent DoWorkEventChanged(sender, e)
    End Sub
    Public Sub BackgroundWorker1_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs)
        RaiseEvent CompleteEventChanged(sender, e)
    End Sub
    Public Event DoWorkEventChanged As System.ComponentModel.DoWorkEventHandler
    Public Event CompleteEventChanged As System.ComponentModel.RunWorkerCompletedEventHandler
#End Region
End Class

sak2005

  • Posts: 972
Mci Player Class:
Code: [Select]
Option Explicit Off
Option Strict On

Imports System
Imports System.Drawing
Imports System.Text
Imports System.IO
Imports System.ComponentModel
Imports System.Windows.Forms
Imports System.Diagnostics
Public Class MciClass
    Inherits Object
    Private Declare Function SendString Lib "winmm.dll" Alias "mciSendStringA" (ByVal lpstrCommand As String, ByVal lpstrReturnString As StringBuilder, ByVal uReturnLength As Integer, ByVal hwndCallback As IntPtr) As Integer
    Private Declare Function GetErrorString Lib "winmm.dll" Alias "mciGetErrorStringA" (ByVal dwError As Integer, ByVal lpstrBuffer As StringBuilder, ByVal uLength As Integer) As Integer
    Private PosTime As Windows.Forms.Timer
    Private strBuffer As StringBuilder = Nothing
    Private sFile As String
    Private hr As Integer
    Public Sub New()
        MyBase.New()
        hr = SendString("open new type waveaudio alias capture", Nothing, 0, IntPtr.Zero)
        hr = SendString("set capture samplespersec 22050", Nothing, 0, IntPtr.Zero)
        hr = SendString("set capture bitspersample 16", Nothing, 0, IntPtr.Zero)
        hr = SendString("set capture channels 2", Nothing, 0, IntPtr.Zero)
        If CBool(hr) Then MsgBox("Error! open waveaudio")
        Me.PosTime = New Windows.Forms.Timer
        PosTime.Interval = 50
        Me.strBuffer = New StringBuilder(128)
        Me.sFile = String.Empty
        AddHandler PosTime.Tick, New EventHandler(AddressOf PosTime_Tick)
    End Sub
    Protected Overrides Sub Finalize()
        MyBase.Finalize()
    End Sub
    Public Overridable Function ErrorMessage(ByVal hr As Integer) As Boolean
        If sFile <> String.Empty Then
            GetErrorString(hr, strBuffer, strBuffer.Capacity)
            If hr <> 0 Then
                MsgBox("Error! " & strBuffer.ToString)
                Return True
            End If
        End If
        Return False
    End Function
    Public Overridable Overloads Function Load(ByVal strFile As String) As Boolean
        If sFile <> String.Empty Then
            hr = SendString("close sound", Nothing, 0, IntPtr.Zero)
            ErrorMessage(hr)
        End If
        sFile = strFile
        Dim hWindow As New Control
        hr = SendString("open """ & sFile & """ type mpegvideo alias sound parent " & hWindow.Handle.ToInt32 & " style child", Nothing, 0, IntPtr.Zero)
        ErrorMessage(hr)
        hr = SendString("setvideo sound off", Nothing, 0, IntPtr.Zero)
        ErrorMessage(hr)
    End Function
    Public Overridable Overloads Function Load(ByVal strFile As String, ByVal window As IntPtr) As Boolean
        If sFile <> String.Empty Then
            hr = SendString("close sound", Nothing, 0, IntPtr.Zero)
            ErrorMessage(hr)
        End If
        sFile = strFile
        Dim hWindow As New Control
        hr = SendString("open """ & sFile & """ type mpegvideo alias sound parent " & window.ToInt32 & " style child", Nothing, 0, IntPtr.Zero)
        ErrorMessage(hr)
        hr = SendString("setvideo sound off", Nothing, 0, IntPtr.Zero)
        ErrorMessage(hr)
    End Function
    Public Overridable Overloads Function SetWindow(ByVal window As IntPtr, ByVal pWidth As Integer, ByVal pHeight As Integer) As Boolean
        hr = SendString("put sound destination at 0 0 " & pWidth & " " & pHeight, Nothing, 0, IntPtr.Zero)
        ErrorMessage(hr)
    End Function
    Public Overridable Overloads Function SetWindow(ByVal window As Control) As Boolean
        hr = SendString("put sound destination at 0 0 " & window.Width & " " & window.Height, Nothing, 0, IntPtr.Zero)
        ErrorMessage(hr)
    End Function
    Public Overridable Overloads Function ResizeWindow(ByVal window As Rectangle) As Boolean
        hr = SendString("put sound window at " & window.Left & " " & window.Top & window.Width & " " & window.Height, Nothing, 0, IntPtr.Zero)
        ErrorMessage(hr)
    End Function
    Public Overridable Function Play(Optional ByVal repeat As Boolean = False) As Boolean
        If sFile <> String.Empty Then
            If repeat Then
                hr = SendString("play sound repeat", Nothing, 0, IntPtr.Zero)
                ErrorMessage(hr)
            Else
                hr = SendString("play sound", Nothing, 0, IntPtr.Zero)
                ErrorMessage(hr)
            End If
            If Not PosTime.Enabled Then PosTime.Start()
        End If
    End Function
    Public Overridable Function Pause(Optional ByVal toggle As Boolean = False) As Boolean
        If sFile <> String.Empty Then
            If toggle Then
                If State() = 1 Then
                    hr = SendString("pause sound", Nothing, 0, IntPtr.Zero)
                    ErrorMessage(hr)
                    bl = True
                Else
                    If State() = 2 Then
                        hr = SendString("resume sound", Nothing, 0, IntPtr.Zero)
                        ErrorMessage(hr)
                        bl = False
                    End If
                End If
            Else
                hr = SendString("pause sound", Nothing, 0, IntPtr.Zero)
                ErrorMessage(hr)
            End If
        End If
    End Function
    Public Overridable Function [Stop]() As Boolean
        If sFile <> String.Empty Then
            hr = SendString("seek sound to 0", Nothing, 0, IntPtr.Zero)
            ErrorMessage(hr)
            hr = SendString("stop sound", Nothing, 0, IntPtr.Zero)
            ErrorMessage(hr)
        End If
    End Function
    Public Overridable Function State() As Integer
        If sFile <> String.Empty Then
            Select Case Status
                Case "stopped"
                    Return 0
                Case "playing"
                    Return 1
                Case "paused"
                    Return 2
                Case Else
                    Return -1
            End Select
        End If
    End Function
    Public Overridable Function SetPosition(ByVal pos As Double) As Boolean
        If sFile <> String.Empty Then
            If IsPlaying Then
                hr = SendString("play sound from " & pos, Nothing, 0, IntPtr.Zero)
                ErrorMessage(hr)
            Else
                hr = SendString("seek sound to " & pos, Nothing, 0, IntPtr.Zero)
                ErrorMessage(hr)
            End If
        End If
    End Function
    Public Overridable Sub Volume(ByVal vol As Integer)
        hr = SendString("setaudio sound volume to " & ((1000 / 100) * vol).ToString(), Nothing, 0, IntPtr.Zero)
        ErrorMessage(hr)
    End Sub
    Public Overridable Sub Balance(ByVal bal As Integer)
        If (bal > 0) Then
            SendString("setaudio sound left volume to " & ((100 - bal) * 10).ToString(), Nothing, 0, IntPtr.Zero)
            ErrorMessage(hr)
        End If
        If (bal < 0) Then
            hr = SendString("setaudio sound right volume to " & ((100 + bal) * 10).ToString(), Nothing, 0, IntPtr.Zero)
            ErrorMessage(hr)
        End If
    End Sub
    Public Overridable ReadOnly Property Status() As String
        Get
            If sFile <> String.Empty Then
                hr = SendString("status sound mode", strBuffer, strBuffer.Capacity, IntPtr.Zero)
                If Not CBool(hr) Then
                    Return strBuffer.ToString
                Else
                    Throw New Exception("Error! status fail")
                End If
            End If
            Return "installed"
        End Get
    End Property
    Public Overridable ReadOnly Property Duration() As Double
        Get
            If sFile <> String.Empty Then
                hr = SendString("status sound length", strBuffer, strBuffer.Capacity, IntPtr.Zero)
                If Not CBool(hr) Then
                    Return Double.Parse(strBuffer.ToString)
                Else
                    Throw New Exception("Error! duration fail")
                End If
            End If
            Return 0
        End Get
    End Property
    Public Overridable ReadOnly Property MaxPosition() As Double
        Get
            If sFile <> String.Empty Then
                Return Duration
            End If
        End Get
    End Property
    Public Overridable ReadOnly Property CurrentPosition() As Double
        Get
            If sFile <> String.Empty Then
                hr = SendString("status sound position", strBuffer, strBuffer.Capacity, IntPtr.Zero)
                If Not CBool(hr) Then
                    Return Double.Parse(strBuffer.ToString)
                Else
                    Throw New Exception("Error! position fail")
                End If
            End If
            Return 0
        End Get
    End Property
    Public Overridable ReadOnly Property IsPlaying() As Boolean
        Get
            If sFile <> String.Empty Then
                If State() = 1 Then
                    Return True
                End If
            End If
            Return False
        End Get
    End Property
    Public Overridable ReadOnly Property IsPaused() As Boolean
        Get
            If sFile <> String.Empty Then
                If State() = 2 Then
                    Return True
                End If
            End If
            Return False
        End Get
    End Property
    Public Overridable ReadOnly Property LevelLeft() As Integer
        Get
            If IsPlaying Then
                hr = SendString("status capture level", strBuffer, strBuffer.Capacity, IntPtr.Zero)
                Return Integer.Parse(strBuffer.ToString) And 65535
            End If
            Return 0
        End Get
    End Property
    Public Overridable ReadOnly Property LevelRight() As Integer
        Get
            If IsPlaying Then
                hr = SendString("status capture level", strBuffer, strBuffer.Capacity, IntPtr.Zero)
                Return (Integer.Parse(strBuffer.ToString) >> 16) And 65535
            End If
            Return 0
        End Get
    End Property
    Public Sub PosTime_Tick(ByVal sender As Object, ByVal e As EventArgs)
        If sFile <> String.Empty Then
            If CurrentPosition < Duration Then
                RaiseEvent PositionChanged(Me, New EventArgs)
            Else
                [Stop]()
            End If
        End If
    End Sub
    Public Event PositionChanged As EventHandler
End Class

sak2005

  • Posts: 972
Tip: DirectSound Capture Level (VolumeMeter) ::)

Example: DSoundLevelClass
Code: [Select]
Public Class DSoundLevelMeter
    Inherits Windows.Forms.Control
#Region "DSoundLevelMeter Constructors"
    Private Const samples As Integer = 8
    Private Shared sampleFormatArray As Integer()
    Private sampleDelay As Integer
    Private clearOnStop As Boolean
    Private _totalCount As Integer
    Private _leftLevel As Integer
    Private _rightLevel As Integer
    Private audioDevices As Microsoft.DirectX.DirectSound.CaptureDevicesCollection
    Private audioDeviceNames As System.Collections.Specialized.StringCollection
    Private audioBuffer As Microsoft.DirectX.DirectSound.CaptureBuffer
    Private signalThread As System.Threading.Thread
    Private currentDeviceName As String
    Private currentDeviceIndex As Integer
    Private _audioMode As AudioMode
    Private _channels As Integer
    Private _maxvalue As Integer
    Public Sub New()
        MyBase.New()
        Windows.Forms.Control.CheckForIllegalCrossThreadCalls = False
        Me._leftLevel = 0
        Me._rightLevel = 0
        Me._totalCount = 15
        Me._maxvalue = 10
        Me.sampleDelay = 50
        Me._audioMode = AudioMode.Stereo
        Me._channels = Me._audioMode
        Me.clearOnStop = True
        SetupAudio()
    End Sub
    Shared Sub New()
        Windows.Forms.Control.CheckForIllegalCrossThreadCalls = False
        sampleFormatArray = New Integer() {8, 2, 1}
    End Sub
#End Region
#Region "DSoundLevelMeter Methods"
    Private Sub SetupAudio()
        Dim devCount As Integer
        Dim v_deviceInformation As Microsoft.DirectX.DirectSound.DeviceInformation
        Me.audioDevices = New Microsoft.DirectX.DirectSound.CaptureDevicesCollection
        Me.audioDeviceNames = New Specialized.StringCollection
        devCount = 0
        Do While (devCount < Me.audioDevices.Count)
            v_deviceInformation = Me.audioDevices(devCount)
            Me.audioDeviceNames.Add(v_deviceInformation.Description)
            devCount += 1
        Loop
        Me.currentDeviceIndex = 1
        Me.currentDeviceName = Me.audioDeviceNames(Me.currentDeviceIndex)
        v_deviceInformation = Me.audioDevices(Me.currentDeviceIndex)
        Dim v_audioCaptureDescription As New Microsoft.DirectX.DirectSound.CaptureBufferDescription
        Dim v_audioFormat As New Microsoft.DirectX.DirectSound.WaveFormat
        v_audioFormat.BitsPerSample = CShort(Me._channels * 8)
        v_audioFormat.SamplesPerSecond = 44100
        v_audioFormat.Channels = CShort(Me._channels)
        v_audioFormat.BlockAlign = (Me._channels * v_audioFormat.BitsPerSample) / 8
        v_audioFormat.AverageBytesPerSecond = v_audioFormat.BlockAlign * v_audioFormat.SamplesPerSecond
        v_audioFormat.FormatTag = Microsoft.DirectX.DirectSound.WaveFormatTag.Pcm
        v_audioCaptureDescription.Format = v_audioFormat
        v_audioCaptureDescription.BufferBytes = 8 * v_audioFormat.BlockAlign
        Me.audioBuffer = New Microsoft.DirectX.DirectSound.CaptureBuffer(v_audioCaptureDescription, New Microsoft.DirectX.DirectSound.Capture(v_deviceInformation.DriverGuid))
    End Sub
    Public Overridable Sub StartMeter()
        If signalThread Is Nothing Then
            If Not Me.audioBuffer.Capturing Then Me.audioBuffer.Start(True)
            Me.signalThread = New Threading.Thread(New Threading.ThreadStart(AddressOf Me.UpdateSignal))
            Me.signalThread.Priority = Threading.ThreadPriority.Lowest
            Me.signalThread.Start()
        End If
    End Sub
    Public Overridable Sub StopMeter()
        If signalThread IsNot Nothing Then
            If audioBuffer.Capturing Then audioBuffer.Stop()
            Me.signalThread.Abort()
            Me.signalThread.Join()
            If Me.clearOnStop Then
                UpdateLevel(0, 0)
            End If
        End If
    End Sub
    Public Overridable Sub Close()
        If signalThread IsNot Nothing Then
            If audioBuffer.Capturing Then audioBuffer.Stop()
            audioBuffer.Dispose()
            signalThread.Abort()
            signalThread.Join()
        End If
        signalThread = Nothing
        audioBuffer = Nothing
    End Sub
    Private Sub UpdateLevel(ByVal _levelL As Integer, ByVal _levelR As Integer)
        Dim v_levelL As Integer
        Dim v_levelR As Integer
        Dim v_bl As Boolean
        v_bl = _levelL >= 0
        If Not v_bl Then
            v_levelL = 0
        Else
            v_bl = _levelL <= Me._totalCount
            If Not v_bl Then
                v_levelL = Me._totalCount
            Else
                If MaxValue <= 10 Then
                    v_levelL = _levelL
                Else
                    If MaxValue > 10 AndAlso MaxValue < 101 Then
                        v_levelL = _levelL * 10
                    End If
                End If
            End If
        End If
        v_bl = _levelR >= 0
        If Not v_bl Then
            v_levelR = 0
        Else
            v_bl = _levelR <= Me._totalCount
            If Not v_bl Then
                v_levelR = Me._totalCount
            Else
                If MaxValue <= 10 Then
                    v_levelR = _levelR
                Else
                    If MaxValue > 10 AndAlso MaxValue < 101 Then
                        v_levelR = _levelR * 10
                    End If
                End If
            End If
        End If
        Select Case _audioMode
            Case AudioMode.Stereo
                Me._leftLevel = v_levelL
                If _leftLevel > MaxValue Then _leftLevel = MaxValue
                Me._rightLevel = v_levelR
                If _rightLevel > MaxValue Then _rightLevel = MaxValue
                OnReportLevel(New ReportLevelArgs(Me._leftLevel, Me._rightLevel))
            Case Else
                Dim LRlevel As Integer = 0
                LRlevel = Me._leftLevel
                LRlevel = Me._rightLevel
                If LRlevel > MaxValue Then LRlevel = MaxValue
                Me._channels = AudioMode.Mono
                OnReportLevel(New ReportLevelArgs(LRlevel, LRlevel))
        End Select
        Windows.Forms.Application.DoEvents()
    End Sub
    Private Sub UpdateSignal()
        Dim v_sampleArray As System.Array
        Dim v_leftMax As Integer
        Dim v_rightMax As Integer
        Dim v_i As Integer
        Do While True
            Try
                v_sampleArray = Me.audioBuffer.Read(0, GetType(Short), Microsoft.DirectX.DirectSound.LockFlag.FromWriteCursor, sampleFormatArray)
            Catch ex As Exception
                v_i = 0
                Return
            End Try
            v_leftMax = 0
            v_rightMax = 0
            v_i = 0
            Do While (v_i < 8)
                v_leftMax += CShort(v_sampleArray.GetValue(v_i, 0, 0))
                v_rightMax += CShort(v_sampleArray.GetValue(v_i, 1, 0))
                v_i += 1
            Loop
            Windows.Forms.Application.DoEvents()
            v_leftMax = System.Math.Abs(v_leftMax / 8)
            v_rightMax = System.Math.Abs(v_rightMax / 8)
            Dim v_Increment As Double = CDbl(32767 / Me._totalCount)
            Me._leftLevel = CInt((CDbl(v_leftMax)) / v_Increment)
            Me._rightLevel = CInt((CDbl(v_rightMax)) / v_Increment)
            UpdateLevel(Me._leftLevel, Me._rightLevel)
            Threading.Thread.Sleep(Me.sampleDelay)
        Loop
    End Sub
    Protected Overridable Sub OnReportLevel(ByVal e As ReportLevelArgs)
        If Not ReportLevelEvent Is Nothing Then
            RaiseEvent ReportLevel(Me, e)
        End If
    End Sub
#End Region
#Region "DSoundLevelMeter AudioMode Fields"
    Public Enum AudioMode
        Mono = 1
        Stereo = 2
    End Enum
#End Region
#Region "DSoundLevelMeter Properties"
    Public Overridable Property AudioDisplayMode() As AudioMode
        Get
            Return Me._audioMode
        End Get
        Set(ByVal Value As AudioMode)
            Me._audioMode = Value
            Me._channels = Value
        End Set
    End Property
    Public Overridable Property ClearMeterOnStop() As Boolean
        Get
            Return Me.clearOnStop
        End Get
        Set(ByVal Value As Boolean)
            Me.clearOnStop = Value
        End Set
    End Property
    Public Overridable Property SampleFrequencyMilliseconds() As Integer
        Get
            Return Me.sampleDelay
        End Get
        Set(ByVal Value As Integer)
            Me.sampleDelay = Value
        End Set
    End Property
    Public Overridable ReadOnly Property TotalCount() As Integer
        Get
            Return Me._totalCount
        End Get
    End Property
    Public Overridable Property MaxValue() As Integer
        Get
            Return Me._maxvalue
        End Get
        Set(ByVal value As Integer)
            Me._maxvalue = value
        End Set
    End Property
#End Region
#Region "DSoundLevelMeter Events"
    Public Event ReportLevel As ReportLevelEventHandler
#End Region
End Class
#Region "DSoundLevelMeter ReportLevelEventHandler Fields"
Public Delegate Sub ReportLevelEventHandler(ByVal sender As Object, ByVal e As ReportLevelArgs)
#End Region
Public Class ReportLevelArgs
    Inherits System.EventArgs
#Region "DSoundLevelMeter ReportLevelArgs Fields"
    Private _leftLevel As Integer
    Private _rightLevel As Integer
#End Region
#Region "DSoundLevelMeter ReportLevelArgs Constructors"
    Public Sub New()
        MyBase.New()
        Me._leftLevel = 0
        Me._rightLevel = 0
    End Sub
    Public Sub New(ByVal _LeftLevel As Integer, ByVal _RightLevel As Integer)
        MyBase.New()
        Me._leftLevel = _LeftLevel
        Me._rightLevel = _RightLevel
    End Sub
#End Region
#Region "DSoundLevelMeter ReportLevelArgs Properties"
    Public ReadOnly Property LeftLevel() As Integer
        Get
            Return Me._leftLevel
        End Get
    End Property
    Public ReadOnly Property RightLevel() As Integer
        Get
            Return Me._rightLevel
        End Get
    End Property
#End Region
End Class
« Last Edit: 30 Aug '17 - 07:23 by sak2005 »