fortran66のブログ

fortran について書きます。

【メモ帳】Windows 上の Fortran で wav file の音を出す

AI 様に書いていただく

AI 様に書いていただいた後、修正を少し加えました。

ソース・プログラム

program DynamicPlaySoundExample
    use, intrinsic :: iso_c_binding
    implicit none

    ! Define the external Windows API functions
    interface
        function LoadLibrary(lpLibFileName) bind(C, name="LoadLibraryA")
            use, intrinsic :: iso_c_binding
            character(kind=c_char, len=1), dimension(*) :: lpLibFileName
            type(c_ptr) :: LoadLibrary
        end function LoadLibrary

        function GetProcAddress(hModule, lpProcName) bind(C, name="GetProcAddress")
            use, intrinsic :: iso_c_binding
            type(c_ptr), value :: hModule
            character(kind=c_char, len=1), dimension(*) :: lpProcName
            type(c_ptr) :: GetProcAddress
        end function GetProcAddress

        subroutine FreeLibrary(hModule) bind(C, name="FreeLibrary")
            use, intrinsic :: iso_c_binding
            type(c_ptr), value :: hModule
        end subroutine FreeLibrary
    end interface

    ! Define the PlaySound function type
    interface
        subroutine PlaySound(lpSound, hModule, dwFlags) bind(C)
            use, intrinsic :: iso_c_binding
            character(kind=c_char, len=1), dimension(*) :: lpSound
            integer(c_int), value :: hModule
            integer(c_int), value :: dwFlags
        end subroutine PlaySound
    end interface

    ! Constants for PlaySound function
    integer, parameter :: SND_FILENAME = 1
    integer, parameter :: SND_ASYNC = 1

    ! Variables for dynamic loading
    type(c_ptr) :: hWinmm, PlaySoundAddr
    procedure(PlaySound), pointer :: PlaySoundPtr

    ! Path to the WAV file
    character(len=:), allocatable :: wavFile
    character(kind=c_char, len=:), allocatable :: libName, funcName, c_wavfile

    ! Initialize variables
    libName = 'winmm.dll' // c_null_char
    funcName = 'PlaySoundA' // c_null_char
    wavFile = "C:\test_audio.wav"  ! Change this path to your WAV file location
    c_wavFile = trim(adjustl(wavFile)) // c_null_char

    ! Load winmm.dll
    hWinmm = LoadLibrary(libName)
    if (.not. c_associated(hWinmm)) then
        print *, 'Failed to load winmm.dll'
        error stop 
    end if

    ! Get the address of PlaySound function
    PlaySoundAddr = GetProcAddress(hWinmm, funcName)
    if (.not. c_associated(PlaySoundAddr)) then
        print *, 'Failed to get address of PlaySoundA'
        call FreeLibrary(hWinmm)
        error stop 
    end if
    call c_f_pointer(PlaySoundAddr, PlaySoundPtr)

    ! Call PlaySound function to play the WAV file
    call PlaySoundPtr(c_wavFile, 0, SND_FILENAME + SND_ASYNC)

    ! Free the library
    call FreeLibrary(hWinmm)

end program DynamicPlaySoundExample