Back to blog
Nov 23, 2024
2 min read

Skyrim: Music Box Script

Make a Music Box in Skyrim.

Steps:

Released mod: BG3 Music Box

  • Attach this script to an activator.
  • Music can be Turned on/off.
  • The music track is actually “Sound” in Creation Kit, Not “Music”. Reason: Music will override each other, but Sound won’t.
  • Music volume changes based on Player distance.
  • *Not a 3D Sound setting.

Script:

1
Scriptname BG3MusicBoxScript extends ObjectReference
2
3
Sound Property MusicSound Auto
4
bool Property isPlaying = false Auto
5
Int instanceID = -1 ; Initialize with an invalid ID
6
7
Float Property MaxDistance = 3000.0 Auto ; Set range for longer fade-out
8
Float Property CheckInterval = 0.25 Auto ; Reduced interval for even smoother updates
9
10
Event OnActivate(ObjectReference akActionRef)
11
if akActionRef == Game.GetPlayer()
12
if isPlaying
13
; Stop the sound instance using the global function
14
if instanceID != -1
15
Sound.StopInstance(instanceID)
16
endif
17
isPlaying = false
18
else
19
; Play the sound and store the instance ID
20
instanceID = MusicSound.Play(self)
21
if instanceID != -1
22
isPlaying = true
23
; Start checking distance
24
RegisterForSingleUpdate(CheckInterval)
25
endif
26
endif
27
endif
28
EndEvent
29
30
Event OnUpdate()
31
if isPlaying
32
; Calculate distance from player
33
float distance = Game.GetPlayer().GetDistance(self)
34
35
; Calculate volume based on distance with a smoother transition
36
float volume = 1.0 - (distance / MaxDistance) ; Linear fade for realistic transition
37
38
; Clamp volume between 0.0 and 1.0
39
if volume < 0.0
40
volume = 0.0
41
elseif volume > 1.0
42
volume = 1.0
43
endif
44
45
; Set the sound volume
46
Sound.SetInstanceVolume(instanceID, volume)
47
48
; Schedule next update
49
RegisterForSingleUpdate(CheckInterval)
50
endif
51
EndEvent