Play recorded sounds

From Rosetta Code
Jump to: navigation, search
Play recorded sounds
You are encouraged to solve this task according to the task description, using any language you may know.

Load at least two prerecorded sounds, and demonstrate as many of these features as you can:

  • playing them individually and simultaneously
  • stopping before the end of the sound
  • looping (preferably glitch-free)
  • setting the volume of each sound
  • stereo or 3D positional mixing
  • performing other actions when marked times in the sound arrive


  • The supported audio formats, briefly.
  • Whether it is suitable for game sound effects (low-latency start, resource efficiency, supports many simultaneous sounds, etc.)
  • Whether it is suitable for playing music (long duration ).

[Note: If it seems to be a good idea, this task may be revised to specify a particular timeline rather than just 'demonstrate these features'.]

Where applicable, please categorize examples primarily by the audio facility used (library/API/program/platform) rather than the language if the language is incidental (e.g. "Mac OS X CoreAudio" or "mplayer" rather than "C" or "bash").


[edit] AutoHotkey

No builtin functions for:
1. monitoring timepoints in the sound
2. simultaneous play

SoundPlay, %A_WinDir%\Media\tada.wav, wait
SoundPlay, %A_WinDir%\Media\Windows XP Startup.wav, wait
; simulaneous play may require a second script
SoundPlay, %A_WinDir%\Media\tada.wav
SoundPlay, Nonexistent ; stop before finishing
SoundSet +10 ; increase volume by 10%
Loop, 2
SoundPlay, %A_WinDir%\Media\tada.wav, wait

[edit] Batch File

It only works on Windows XP and it only reads Wave (.wav) audio files:

 @echo off
 echo Drag a .wav file there and press enter
 set /p file1=
 sndrec32 /embedding /play /close %file1%
 echo Drag a second .wav file and both will play together
 set /p file2=
 sndrec32 /embedding /play /close %file1% | sndrec32 /embedding /play /close %file2%
 echo Thanks

[edit] BBC BASIC

BBC BASIC for Windows has native support for playing MIDI files, and WAV files can be played using simple API calls:

      SND_LOOP = 8
PRINT "Playing a MIDI file..."
*PLAY C:\windows\media\canyon.mid
WAIT 300
PRINT "Playing the Windows TADA sound quietly..."
wave$ = "\windows\media\tada.wav"
volume% = 10000
SYS "waveOutSetVolume", -1, volume% + (volume% << 16)
SYS "PlaySound", wave$, 0, SND_FILENAME + SND_ASYNC
WAIT 300
PRINT "Playing the Windows TADA sound loudly on the left channel..."
volume% = 65535
SYS "waveOutSetVolume", -1, volume%
SYS "PlaySound", wave$, 0, SND_FILENAME + SND_ASYNC
WAIT 300
PRINT "Playing the Windows TADA sound loudly on the right channel..."
volume% = 65535
SYS "waveOutSetVolume", -1, volume% << 16
SYS "PlaySound", wave$, 0, SND_FILENAME + SND_ASYNC
WAIT 300
PRINT "Looping the Windows TADA sound on both channels..."
volume% = 65535
SYS "waveOutSetVolume", -1, volume% + (volume% << 16)
SYS "PlaySound", wave$, 0, SND_FILENAME + SND_ASYNC + SND_LOOP
WAIT 300
SYS "PlaySound", 0, 0, 0
PRINT "Stopped looping..."
WAIT 300
PRINT "Stopped MIDI."

[edit] C#

using System;
using System.Threading;
using System.Media;
class Program
static void Main(string[] args)
//load sound file
SoundPlayer s1 = new SoundPlayer(); //
s1.SoundLocation = file; // or "s1 = new SoundPlayer(file)"
//play for 0.1 seconds

[edit] Delphi

program PlayRecordedSounds;
uses MMSystem;
sndPlaySound('SoundFile.wav', SND_NODEFAULT OR SND_ASYNC);

[edit] GUISS

Here we use the media player to play a sound file in the default directory:

Start,Programs,Accessories,Media Player,Menu:File,Open,

[edit] Liberty BASIC

'Supports .mid and .wav natively
'Midi may be played simultaneously
'with .wav but only one .wav voice
'is supported. Multiple voices can
'be achieved via API or Dlls such
'as FMOD or Wavemix
'to play a .mid and return its length
playmidi "my.mid", midiLength
'check where we are in .mid
if midipos()<midiLength then
print "Midi still playing"
print "Midi ended"
end if
'to stop a playing .mid
'to play a .wav and wait for it to end
playwave "my.wav"
'to play a .wav and continue procesing
playwave "my.wav", async
'to loop a .wav and continue processing
playwave "my.wav",loop
'to silence any .wav
playwave ""
playwave "next.wav"
'to adjust .wav vol
'set left and right full on
left =65535
calldll #winmm, "waveOutSetVolume", 0 as long, _
dwVol as long, ret as long

[edit] Mathematica

This code demonstrates : loading two prerecorded sounds,playing them individually then simultaneously, stopping before the end of the sound,looping (preferably glitch-free)and setting the volume of each sound

a = Import["sound1.flac","FLAC"]; b = Import["sound2.flac","FLAC"];
ListPlay[a, {t, 0, 10}]; ListPlay[b, {t, 0, 10}];
ListPlay[{a,b}, {t, 0, 10}];
Stopping before the end can be done using the GUI or by reducing the parameter range of the ListPlay function.
While[True,ListPlay[{a,b}, {t, 0, 10}];]
ListPlay[{0.5*a, 0.3*b}, {t, 0, 10}];

-Supported audio formats : AIFF Macintosh sound format (.aif, .aiff), AU Mu law encoding Unix Audio Format (.au), FLAC lossless audio codec (.flac), SND file format, equivalent to AU (.snd), "WAV" WAV format (.wav), "Wave64" Sony Wave64 format (.w64), MIDI format (.mid)

-Suitability for game sound effects : low-latency start : yes resource efficiency : low support for many simultaneous sounds : yes

-Suitable for playing sound of arbitrary long duration.

[edit] PicoLisp

The obvious way is to call 'sox', the "Swiss Army knife of audio manipulation" (man sox).

The following plays two files "a.wav" and "b.wav" simultaneously (to play them individually, omit the "-m" flag). The first one is played with a volume of 75 percent, the second with 25 percent, starting at the 4th second, with a duration of 6 seconds, looping 5 times.

(call 'sox
"-m" "-v" "0.75" "a.wav" "-v" "0.25" "b.wav"
"trim" 4 6
"repeat" 5 )

[edit] PureBasic

; We need this to use Sound functions
; Now we can not only load wav sound files, but also ogg encoded ones.
; With movie library more formats can be played (depends on system) but you cannot
; handle them with Sound functions
If Not LoadSound(1,"Path/to/Sound/1.ogg") Or Not LoadSound(2,"Path/to/Sound/2.wav")
MessageRequester("Error","One of our sounds could not be loaded"+Chr(10)+"Use Debugger to check which one")
;- simultaneous playing
;- manipulating sounds
; pause for one second, to let user hear something
; reduce volume of the sounds a bit
; Sound 1 mostly left speaker, sound 2 only right speaker
; play sound one faster
; pause for one second, to let user hear effects of previous actions
;- stopping while playing
; value -1 stops all playing sounds
; continous looping without glitch
;suitable for 2D games and music playing.
; TODO: There is a Sound3D library for 3D Games, needs to be decribed here too

[edit] Python

Works with: Python version 2.6
Library: pygame

Pygame is a library for cross-platform game development and depends on the SDL multimedia library (SDL_mixer) for its audio playback. SDL_mixer supports any number of simultaneously playing channels of 16 bit stereo audio, plus a single channel of music, mixed by the popular MikMod MOD, Timidity MIDI, Ogg Vorbis, and SMPEG MP3 libraries.

import time
from pygame import mixer
mixer.init(frequency=16000) #set frequency for wav file
s1 = mixer.Sound('test.wav')
s2 = mixer.Sound('test2.wav')
#individual #loops indefinitely
#simultaneously #play once
time.sleep(2) #optional parameter loops three times
#set volume down
#set volume up

To play back .mp3 (or .ogg) files, the music import is used.

import time
from pygame import mixer
from pygame.mixer import music

[edit] R

Library: sound

R's sound package uses system commands to call a built-in media player. On Windows, by default, this is Media Player. You can see the system call with WavPlayer(). Only .WAV files are supported, and the external code call means there is some latency before sounds are played. Samples longer than 10 minutes may correspond to significant chunks of your machine's memory.

# Warning: The example files are Windows specific.
media_dir <- file.path(Sys.getenv("SYSTEMROOT"), "Media")
chimes <- loadSample(file.path(media_dir, "chimes.wav"))
chord <- loadSample(file.path(media_dir, "chord.wav"))
# Play sequentially
play(appendSample(chimes, chord))
# Play simultaneously
play(chimes + chord)
# Stopping before the end
play(cutSample(chimes, 0, 0.2))
for(i in 1:3) play(chimes) #leaves a gap between instances
three_chimes <- lapply(vector(3, mode = "list"), function(x) chimes)
play(, three_chimes)) #no gap, see also cutSampleEnds
# Volume control
play(3 * chimes)
#Stereo effect
play(stereo(chimes, chord))
#Other actions (not obviously possible)

[edit] Racket

(Works on all platforms.)

#lang racket/gui
(play-sound "some-sound.wav" #f)

[edit] Ruby

There aren't many mature sound libraries for Ruby. The
Library: RubyGems
package win32-sound can play WAV files on the Windows platform only.
require 'win32/sound'
include Win32
sound1 = ENV['WINDIR'] + '\Media\Windows XP Startup.wav'
sound2 = ENV['WINDIR'] + '\Media\Windows XP Shutdown.wav'
puts "play the sounds sequentially"
[sound1, sound2].each do |s|
t1 =
puts "'#{s}' duration: #{( - t1.to_f)} seconds"
puts "attempt to play the sounds simultaneously"
[sound1, sound2].each {|s|, Sound::ASYNC)}
puts <<END
the above only plays the second sound2 because the library only appears
to be able to play one sound at a time.

puts "loop a sound for a few seconds"
puts, Sound::ASYNC + Sound::LOOP)
sleep 10
puts "manipulate the volume"
vol_left, vol_right = Sound.wave_volume, Sound::ASYNC)
sleep 1
puts "right channel quiet"
Sound.set_wave_volume(vol_left, 0)
sleep 1
puts "left channel quiet"
Sound.set_wave_volume(0, vol_right)
sleep 1
puts "restore volume"
Sound.set_wave_volume(vol_left, vol_right)
sleep 1
puts "the asynchronous sound is cancelled when the program exits"

[edit] Swift

Uses AVFoundation's AVAudioPlayer.

import AVFoundation
// This example uses AVAudioPlayer for playback.
// AVAudioPlayer is the player Apple recommends for playback, since it suitable for songs
// and offers control over numerous playback parameters.
// It can play any type that is natively supported by OSX or iOS
class PlayerControl: NSObject, AVAudioPlayerDelegate {
let player1:AVAudioPlayer!
let player2:AVAudioPlayer!
var playedBoth = false
var volume:Float {
get {
return player1.volume
set {
player1.volume = newValue
player2.volume = newValue
init(player1:AVAudioPlayer, player2:AVAudioPlayer) {
self.player1 = player1
self.player2 = player2
self.player1.delegate = self
self.player2.delegate = self
func loop() {
player1.numberOfLoops = 1
let time = Int64((Double(player1.duration) + 2.0) * Double(NSEC_PER_SEC))
dispatch_after(dispatch_time(0, time), dispatch_get_main_queue()) {[weak self] in
println("Stopping track")
func playBoth() {
func audioPlayerDidFinishPlaying(player:AVAudioPlayer!, successfully flag:Bool) {
if player === player2 && !playedBoth {
playedBoth = true
} else if player === player2 && playedBoth {
let url1 = NSURL(string: "file:///file1.mp3")
let url2 = NSURL(string: "file:///file2.mp3")
var err:NSError?
let player1 = AVAudioPlayer(contentsOfURL: url1, error: &err)
let player2 = AVAudioPlayer(contentsOfURL: url2, error: &err)
let player = PlayerControl(player1: player1, player2: player2)
// Setting the volume
player.volume = 0.5
// Play track 2
// When this track finishes it will play both of them
// by calling the audioPlayerDidFinishPlaying delegate method
// Once both tracks finish playing, it will then loop the first track twice
// stopping the track after 2 seconds of the second play

[edit] Tcl

Library: snack
package require sound
# Potentially also require driver support for particular formats
# Load some sounds in; this part can be slow
snack::sound s1
s1 read $soundFile1
snack::sound s2
s2 read $soundFile2
# Play a sound for a while (0.1 seconds; this is a low-latency operation)
s1 play
after 100 set done 1; vwait done; # Run the event loop for a while
s1 stop
# Play two sounds at once (for 30 seconds) while mixing together
s1 play
s2 play
after 30000 set done 1; vwait done
s1 stop
s2 stop

Note that this library is capable of handling both short and long sounds (sound effects and music).


ERROR/STOP OPEN (audiofile,READ,-std-)
BROWSE $audiofile

[edit] UNIX Shell

# Plays .au files.
# Usage: <>
cat $1 >> /dev/audio # Write file $1 to the speaker's Character Special (/dev/audio).

[edit] VBA

Visual Basic for Applications can play sounds in the .WAV format by calling the multimedia library winmm.dll. See The "Flags" parameter can be used e.g. to play a sound continuously (that is, until the function is called again to stop playing).

Volume can be set using the function waveOutSetVolume, see

Declare Function libPlaySound Lib "winmm.dll" Alias "sndPlaySoundA" _
(ByVal filename As String, ByVal Flags As Long) As Long
Sub PlaySound(sWav As String)
Call libPlaySound(sWav, 1) '1 to play asynchronously
End Sub
Playsound "d:\explode.wav"
in the Immediate window and that sound will play. Nothing will happen if the file d:\explode.wav does not exist.
Personal tools