#include <Bass.au3>
#include <GuiListView.au3>
#include <WindowsConstants.au3>
#include <GUIConstantsEx.au3>
#include <ListViewConstants.au3>
#include <BassConstants.au3>
#include <StructureConstants.au3>

Global $hMusic
Global $hlistview
Global $Playingstate = -1
Global $hslider
Global $fftstruct = DllStructCreate("float[128]")
Global $gaDropFiles[1]
Global $aItem[2]
Global $Arraytoplay[1]
Global $titelnummer
Global Const $WM_DROPFILES = 0x0233

; #FUNCTION# ======================================================================================
; Name ..........: _musicmodul_main()
; Description ...: Eine Funktion zum bauen eines musikplayers
; Syntax ........: _musicmodul_main($Dllpath, $playbutton, $pausebutton, $stopbutton, $volumeslider, $progressprogr[, $newfilebutton = ""[, $hlistview = ""[, $playlisteplay = ""[, $applicationname = @ScriptName]]]])
; Parameters ....: $Dllpath         - Der Pfad zu den DLLs mit abschließendem "\"
;                  $playbutton      - Der Playbutton
;                  $pausebutton     - Der Pausebutton
;                  $stopbutton      - Der Stopbutton
;                  $volumeslider    - Der Lautstärkeslider
;                  $progressprogr   - Der Progress zum anzeigen des Liedfortschrittes
;                  $newfilebutton   - [optional] Der Button zum öffnen einer neuen Datei (default:"")
;                  $hlistview       - [optional] Das Playlistelistview (default:"")
;                  $playlisteplay   - [optional] Der button zum starten der Playliste (default:"")
;                  $applicationname - [optional] Der Name der Anwendung (default:@ScriptName)
; Author ........: JuraX
; Remarks .......: Der Lautstärkeregler muss die variable $hSlider haben| bei einer playliste muss das listview $hlistview sein sein und an den Width parameter muss bei guicreate folgendes angehängt werden:  [, -1, -1, Default, $WS_EX_ACCEPTFILES]
; Link ..........: http://autoit.de/index.php?form=PostAdd&threadID=19334
; Example .......: Yes
;                  #include <ButtonConstants.au3>
;                  #include <GUIConstantsEx.au3>
;                  #include <ListViewConstants.au3>
;                  #include <ProgressConstants.au3>
;                  #include <SliderConstants.au3>
;                  #include <WindowsConstants.au3>
;                  #include <musicplayer_UDF.au3>
;                  $Form1 = GUICreate("Form1", 625, 426, 192, 124 , Default, $WS_EX_ACCEPTFILES)
;                  $Button1 = GUICtrlCreateButton("Play/Pause", 32, 24, 89, 33)
;                  $Button2 = GUICtrlCreateButton("Stop", 184, 24, 97, 33)
;                  $Button3 = GUICtrlCreateButton("Neue Datei", 360, 24, 81, 33)
;                  $hSlider = GUICtrlCreateSlider(0, 88, 625, 49)
;                  $hlistview = GUICtrlCreateListView("Dateiname|Pfad", 8, 176, 601, 233)
;                  $Progress1 = GUICtrlCreateProgress(16, 128, 521, 33)
;                  $playplayliste = GUICtrlCreateButton("Playliste Abspielen",500,24)
;                  GUISetState(@SW_SHOW)
;                  _musicmodul_main(@ScriptDir & "\sys\", $Button1, $Button1, $Button2, $hSlider, $Progress1, $Button3, $hlistview,$playplayliste)
; =================================================================================================

Func _musicmodul_main($Dllpath, $playbutton, $pausebutton, $stopbutton, $volumeslider, $progressprogr, $newfilebutton = "", $hlistview = "", $playlisteplay = "", $applicationname = @ScriptName)

	Opt("GUIOnEventMode", 1)
	Opt("GUIEventOptions", 1)

	Const $dll = $Dllpath
	Global $hlistviewout = $hlistview

    _GetVolslider() ; Static Variable setzen
	_Getplayliste($hlistview) ; Static Variable setzen


	_BASS_STARTUP($dll & "bass.dll")
	_BASS_Init(0, -1, 44100, 0, "")

	If $playbutton = $pausebutton Then
		$Play_ggl_Pause = True
	EndIf

	If $playbutton = "" Or $pausebutton = "" Or $stopbutton = "" Or $volumeslider = "" Or $progressprogr = "" Then
		Return SetError(1, 1, 1)
	EndIf


	Global Const $APPpfad = @AppDataCommonDir & "\" & $applicationname & "\"
	Global Const $App_INI = $APPpfad & "\" & $applicationname & ".ini"

	#region Firststart
	$FirstStart = IniRead($App_INI, "BOOT", "Firtsstart", "")
	Local $FS
	If $FS = "" Then
		DirCreate($APPpfad)
		IniWrite($App_INI, "BOOT", "Firtsstart", "False")
	EndIf
	#endregion Firststart

	If $Play_ggl_Pause = True Then
		GUICtrlSetOnEvent($playbutton, "Playpause")
	Else
		GUICtrlSetOnEvent($playbutton, "play")
		GUICtrlSetOnEvent($pausebutton, "Pause")
	EndIf
	GUICtrlSetOnEvent($stopbutton, "stop")
	GUICtrlSetOnEvent($volumeslider, "Volumechange")

	If $newfilebutton = "" Then
		$file = FileOpenDialog("Datei öffnen:...", "", "MP3 (*.mp3)")
		$hMusic = _BASS_StreamCreateFile(False, $file, 0, 0, 0)
		_Bass_ChannelPlay($hMusic, False)
		$Playingstate = 1
	Else
		GUICtrlSetOnEvent($newfilebutton, "openfile")
	EndIf

	If $hlistview = "" Then
	Else
		$playliste = True
		GUIRegisterMsg($WM_NOTIFY, "WM_NOTIFY")
		GUIRegisterMsg($WM_DROPFILES, 'WM_DROPFILES_FUNC')
	EndIf

	If $playlisteplay = "" Then
	Else
		GUICtrlSetOnEvent($playlisteplay, "Startplayliste")
	EndIf
	#region OnEvent
	GUISetOnEvent($GUI_EVENT_CLOSE, "Windows_Event")
	GUISetOnEvent($GUI_EVENT_MINIMIZE, "Windows_Event")
	GUISetOnEvent($GUI_EVENT_RESTORE, "Windows_Event")
	#endregion OnEvent


	While 1
SoundSetWaveVolume(50)
	$nmsg = GUIGetMsg()
		Switch $nmsg
			Case $GUI_EVENT_DROPPED
				For $i = 0 To UBound($gaDropFiles) - 1
					GUICtrlCreateListViewItem(StringRegExpReplace($gaDropFiles[$i], '.*\\(.*)\..*', '$1'), $hlistview)
					_GUICtrlListView_SetColumnWidth($hlistview, 0, $LVSCW_AUTOSIZE)
				Next
		EndSwitch
		If $Playingstate = 1 Then
			$song_length = _BASS_ChannelGetLength($hMusic, $BASS_POS_BYTE)
			$current = _BASS_ChannelGetPosition($hMusic, $BASS_POS_BYTE)
			$percent = Round(($current / $song_length) * 100, 0)
			GUICtrlSetData($progressprogr, $percent)

			If $current = $song_length Then
				GUICtrlSetData($progressprogr, 0)
				_BASS_ChannelPlay($hMusic, True)

				If IsArray($Arraytoplay) Then
					If $current = $song_length Then
						GUICtrlSetData($progressprogr, 0)
						If $Playingstate = 1 Then
							_BASS_ChannelStop($hMusic)
						EndIf
						$titelnummer += 1
						If $titelnummer > UBound($Arraytoplay, 1) - 1 Then $titelnummer = 0
						$Playingstate = 1
						$hMusic = _BASS_StreamCreateFile(False, $Arraytoplay[$titelnummer], 0, 0, 0)
						_BASS_ChannelPlay($hMusic, 0)
					EndIf

				EndIf
			EndIf
		EndIf
	WEnd

EndFunc   ;==>_musicmodul_main

#region OnEventMode
Func Windows_Event()
	Select
		Case @GUI_CtrlId = $GUI_EVENT_CLOSE
			Shutdownapp()

		Case @GUI_CtrlId = $GUI_EVENT_MINIMIZE
			GUISetState(@SW_MINIMIZE)

		Case @GUI_CtrlId = $GUI_EVENT_RESTORE
			GUISetState(@SW_RESTORE)
	EndSelect
EndFunc   ;==>Windows_Event

Func Shutdownapp()
	_BASS_STOP()
	_BASS_FREE()
	Exit
EndFunc   ;==>Shutdownapp

Func Playpause()
	If $Playingstate = 1 Then
		_Bass_ChannelPause($hMusic)
		$Playingstate = 2
	ElseIf $Playingstate = 2 Then
		_Bass_ChannelPlay($hMusic, False)
		$Playingstate = 1
	EndIf
EndFunc   ;==>Playpause

Func play()
	If $Playingstate = 2 Then
		_Bass_ChannelPlay($hMusic, False)
		$Playingstate = 1
	EndIf
EndFunc   ;==>play

Func Pause()
	If $Playingstate = 1 Then
		_Bass_ChannelPause($hMusic)
		$Playingstate = 2
	EndIf
EndFunc   ;==>Pause

Func Stop()
	If $Playingstate = 1 Or 2 Then
		_Bass_ChannelStop($hMusic)
		$Playingstate = -1
	EndIf
EndFunc   ;==>Stop

Func Volumechange()
	$vol = GUICtrlRead(_GetVolslider())
	SoundSetWaveVolume($vol)
EndFunc   ;==>Volumechange

Func Openfile()
	If $Playingstate = 1 Or 2 Then
		_Bass_ChannelStop($hMusic)
		$Playingstate = -1
	EndIf
	$SelectedFile = FileOpenDialog("MP3-Datei öffnen...", "", "Mp3 (*.mp3)")
	$hMusic = _BASS_StreamCreateFile(False, $SelectedFile, 0, 0, 0)
	_Bass_ChannelPlay($hMusic, False)
	$Playingstate = 1
EndFunc   ;==>Openfile

Func Startplayliste()
	$titelnummer = 0
	If $Playingstate = 1 Then
		_BASS_ChannelStop($hMusic)
		$Playingstate = -1
	EndIf
	$Read = GUICtrlRead(_Getplayliste())
	$sString = ""
	ReDim $Arraytoplay[_GUICtrlListView_GetItemCount(_Getplayliste())]
	For $i = 0 To _GUICtrlListView_GetItemCount(_Getplayliste()) - 1
		$Result = StringSplit(_GUICtrlListView_GetItemTextString(_Getplayliste(), $i), "|")
		$Arraytoplay[$i] = $Result[2]
	Next
	$Playingstate = 1
	$hMusic = _BASS_StreamCreateFile(False, $Arraytoplay[$titelnummer], 0, 0, 0)
	_BASS_ChannelPlay($hMusic, True)
EndFunc   ;==>Startplayliste
#endregion OnEventMode

#region other
Func WM_DROPFILES_FUNC($hwnd, $MSGID, $WPARAM, $LPARAM)
	Local $NSIZE, $PFILENAME
	Local $NAMT = DllCall("shell32.dll", "int", "DragQueryFileW", "hwnd", $WPARAM, "int", -1, "ptr", 0, "int", 255)
	For $i = 0 To $NAMT[0]
		$NSIZE = DllCall("shell32.dll", "int", "DragQueryFileW", "hwnd", $WPARAM, "int", $i, "ptr", 0, "int", 0)
		$NSIZE = $NSIZE[0] + 1
		$PFILENAME = DllStructCreate("wchar[" & $NSIZE & "]")
		DllCall("shell32.dll", "int", "DragQueryFileW", "hwnd", $WPARAM, "int", $i, "ptr", DllStructGetPtr($PFILENAME), "int", $NSIZE)
		$FILENAME = DllStructGetData($PFILENAME, 1)
		ConsoleWrite($FILENAME & @CRLF)
		ReDim $gaDropFiles[$i + 1]
		$gaDropFiles[$i] = DllStructGetData($PFILENAME, 1)
		$PFILENAME = 0
	Next
	For $i = 0 To UBound($gaDropFiles) - 2
		GUICtrlCreateListViewItem(StringRegExpReplace($gaDropFiles[$i], ".*\\(.*)\..*", "$1") & "|" & $gaDropFiles[$i], _Getplayliste())
	Next
	_GUICtrlListView_SetColumnWidth(_Getplayliste(), 0, $LVSCW_AUTOSIZE)
EndFunc   ;==>WM_DROPFILES_FUNC

Func WM_NOTIFY($hwnd, $MSGID, $WPARAM, $LPARAM)
	Local $TAGNMHDR, $EVENT, $HWNDFROM, $CODE
	$TAGNMHDR = DllStructCreate("int;int;int", $LPARAM)
	If @error Then Return 0
	$CODE = DllStructGetData($TAGNMHDR, 3)
	If $WPARAM = _Getplayliste() And $CODE = -3 And _GUICtrlListView_GetSelectedCount(_Getplayliste()) > 0 Then
		For $i = 0 To _GUICtrlListView_GetItemCount(_Getplayliste())
			If _GUICtrlListView_GetItemSelected(_Getplayliste(), $i) Then
				$aItem = _GUICtrlListView_GetItemTextArray(_Getplayliste(), $i)
				_LEFTDBLCLICK()
			EndIf
		Next
	EndIf
	Return $GUI_RUNDEFMSG
EndFunc   ;==>WM_NOTIFY

Func _LEFTDBLCLICK()
	$titelnummer = 0
	If $Playingstate = 1 Or 2 Then
		_BASS_CHANNELSTOP($hMusic)
	EndIf
	$Playingstate = -1
	$file = $aItem[2]
	$hMusic = _BASS_STREAMCREATEFILE(False, $file, 0, 0, 0)
	_BASS_CHANNELPLAY($hMusic, 0)
	$Playingstate = 1
EndFunc   ;==>_LEFTDBLCLICK

Func _GetVolslider($id=0)
    ; ========= Verteilerfunktion. Beinhaltet Static Variable, die einen wichtigen Array, ==========
    ; ========= oder eine wichtige Variable speichert. Wird ein Parameter übergeben, über- ==========
    ; ========= nimmt die Static Variable den Wert. ==========
    Local Static $iCtrlId
    If $id <> 0 Then ; Static Variable ändern
        $iCtrlId = $id
        Return 0
    EndIf
    Return $iCtrlId
EndFunc

Func _Getplayliste($id=0)
    ; ========= Verteilerfunktion. Beinhaltet Static Variable, die einen wichtigen Array, ==========
    ; ========= oder eine wichtige Variable speichert. Wird ein Parameter übergeben, über- ==========
    ; ========= nimmt die Static Variable den Wert. ==========
    Local Static $iCtrlId
    If $id <> 0 Then ; Static Variable ändern
        $iCtrlId = $id
        Return 0
    EndIf
    Return $iCtrlId
EndFunc
#endregion other