Skip to content

Commit

Permalink
(#16) Music: use common sound volume control
Browse files Browse the repository at this point in the history
  • Loading branch information
ForNeVeR committed Aug 17, 2024
1 parent 9bd756e commit 7d1551f
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 13 deletions.
1 change: 1 addition & 0 deletions O21.Game/Game.fs
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ type Game(window: WindowParameters, content: LocalContent, data: U95Data) =
SetSoundVolume(effect, state.Settings.SoundVolume)
PlaySound(effect)

state.MusicPlayer |> Option.iter _.SetVolume(state.Settings.SoundVolume)
state <- { state with SoundsToStartPlaying = Set.empty }

member _.Draw() =
Expand Down
28 changes: 15 additions & 13 deletions O21.Game/Music.fs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
module O21.Game.Music

open System
open System.Threading
open System.Threading.Tasks

open JetBrains.Lifetimes
Expand All @@ -14,21 +15,22 @@ open Raylib_CsLo
let private SampleRate = 44100
let BufferSize = 4096

[<Struct>]
type MusicPlayer =
val mutable Buffer: int16[]
val mutable Stream: AudioStream
val mutable Sequencer: MidiFileSequencer
type MusicPlayer(buffer: int16[], stream: AudioStream, sequencer: MidiFileSequencer) =
let mutable soundVolume = 0.0f

member this.Initialize(): unit =
Raylib.PlayAudioStream this.Stream
member _.Initialize(): unit =
Raylib.PlayAudioStream stream

member this.NeedsPlay(): bool =
Raylib.IsAudioStreamProcessed this.Stream
member _.SetVolume(volume: float32): unit =
Volatile.Write(&soundVolume, volume)

member _.NeedsPlay(): bool =
Raylib.IsAudioStreamProcessed stream

member this.Play(): unit =
this.Sequencer.RenderInterleavedInt16(this.Buffer.AsSpan())
Raylib.UpdateAudioStream(this.Stream, this.Buffer.AsSpan(), BufferSize)
member _.Play(): unit =
sequencer.RenderInterleavedInt16(buffer.AsSpan())
Raylib.SetAudioStreamVolume(stream, Volatile.Read(&soundVolume))
Raylib.UpdateAudioStream(stream, buffer.AsSpan(), BufferSize)

let CreateMusicPlayerAsync (lifetime: Lifetime) (soundFontPath: string, midiFilePath: string) : Task<MusicPlayer> =
task {
Expand All @@ -52,7 +54,7 @@ let CreateMusicPlayerAsync (lifetime: Lifetime) (soundFontPath: string, midiFile
Raylib.StopAudioStream stream
Raylib.UnloadAudioStream stream)
let buffer = Array.zeroCreate(BufferSize * 2)
return MusicPlayer(Buffer = buffer, Stream = audioStream, Sequencer = sequencer)
return MusicPlayer(buffer, audioStream, sequencer)
}

let UpdateMusicPlayer (lifetime: Lifetime) (player:inref<MusicPlayer>) =
Expand Down

0 comments on commit 7d1551f

Please sign in to comment.