Fortran sound playback - platform-independent

Some Fortran code used proprietary modules from Visual Fortran and the like for among other things, playing back sound from Fortran on Windows. I believe a more reliable and platform-independent way to playback sound from Fortran is to use an external application like ffplay, included with FFmpeg.

FFplay will play prerecorded audio files. Playback particular sounds based on filename.

This technique is not good for background music in a game, but is good for short sound effects to let you know your processing is done or for game sound effects in Fortran.

NOTE: use all lowercase filename, and don’t use spaces in names for best cross-platform compatibility and reliability.

Fortran program with sound example: use / as a file/directory separator on Fortran. // concatenates strings in Fortran.

program mysound

use iso_fortran_env, only : input_unit

implicit none

! configure ffplay -- could make if/else to allow other players
character(*), parameter :: playexe='ffplay'
character(*), parameter :: cmdopts='-autoexit -loglevel quiet -nodisp'

character(1000) :: fn, cmd

print *,'input sound filename to play'
read(input_unit,'(A)') fn  ! must be (A) and not *

cmd = playexe//' '//cmdopts//' '//trim(fn)
print *,trim(cmd) ! for debugging

! exitstat only works for wait=.true. by Fortran standard.
call execute_command_line(cmd, wait=.false.)

end program

More Fortran sound playback examples: robust Fortran sound playback example play_sound.f90 or implemented as a Fortran game with sound sound.f90.