Version

Goal:Play an audio file from the filesystem
Difficulty:Beginner
Duration:5 minutes
Language:All

Note: In this tutorial the audio file content is fully loaded in memory. Compressed or generated formats (ogg, mp3, xm, mod, etc...) need to be converted to PCM by the LoadSound before it returns.

For long audio files streaming should be preferred (see Stream sound).

Python

# Load an audio file as a static sound and replay it

import os
import harfang as hg
import time

hg.LoadPlugins()

# mount the system file driver
hg.MountFileDriver(hg.StdFileDriver())

# create a new sound mixer
mixer = hg.CreateMixer()
mixer.Open()

# load a sound
sound = mixer.LoadSound(os.path.join(os.getcwd(), "../_data/good_evening.wav"))

# play the sound
channel = mixer.Start(sound)
print("Sound playing on channel: %d" % channel)

while mixer.GetPlayState(channel) == hg.MixerPlaying:
    time.sleep(0.1)  # pause until the sound is done playing

mixer.Close()

Lua

-- Load an audio file as a static sound and replay it

hg = require("harfang")

hg.LoadPlugins()

-- mount the system file driver
hg.MountFileDriver(hg.StdFileDriver())

-- create a new sound mixer
mixer = hg.CreateMixer()
mixer:Open()

-- load a sound
sound = mixer:LoadSound('../_data/good_evening.wav')

-- play the sound
channel = mixer:Start(sound)
print("Sound playing on channel: "..channel)

while mixer:GetPlayState(channel) == hg.MixerPlaying do
    hg.Sleep(hg.time_from_ms(100))
end

mixer:Close()