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.

This means you will have prerecorded audio files (as games using these Windows media libraries often did), and you’ll 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.

This code assumes you’ve recorded a file sound/oops.wav beforehand.

program mysound
use iso_fortran_env
implicit none (type, external)

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

character(1000) :: fn
character(1000) :: cmd

print *,'input sound file to playback'
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 2008 spec.
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.