How do you play audio from a wav or mp3 file? #14974
MrMidnightOfficial
started this conversation in
General
Replies: 2 comments 3 replies
-
|
https://github.com/vlang/v/tree/master/examples/sokol/sounds |
Beta Was this translation helpful? Give feedback.
2 replies
-
|
For someone who's trying to find a way to play audio using only the standard modules with the raw bindings, there's a possible way to do this: module main
import sokol.audio
import encoding.vorbis
import time
import os
struct AudioData {
mut:
samples []f32
pos int
}
fn main() {
if os.args.len != 2 {
eprintln('usage: <oggfile.ogg>')
exit(1)
}
file_path := os.args[1]
if !os.exists(file_path) {
panic('File missing or not found!')
}
song := vorbis.decode_file(file_path) or { panic('Failed to load file: ${err}') }
defer { unsafe { song.free() } }
println('Loaded: ${song.path}')
println('Sample Rate: ${song.sample_rate}')
println('Channels: ${song.channels}')
println('Samples: ${song.sample_len}')
samples_f32 := []f32{cap: song.sample_len * song.channels}
unsafe {
for i in 0 .. song.sample_len * song.channels {
samples_f32 << f32(song.data[i]) / 32768.0
}
}
audio_data := AudioData{
samples: samples_f32
pos: 0
}
audio.setup(
sample_rate: song.sample_rate
num_channels: song.channels
stream_userdata_cb: audio_stream_callback
user_data: voidptr(&audio_data)
)
println('Playing...')
mut last_print_time := time.now()
for {
now := time.now()
if now - last_print_time >= time.second {
current_sec := (audio_data.pos / song.channels) / song.sample_rate
total_sec := (audio_data.samples.len / song.channels) / song.sample_rate
println('Current time: ${current_sec}s / ${total_sec}s')
last_print_time = now
}
if audio_data.pos >= audio_data.samples.len {
break
}
time.sleep(100 * time.millisecond)
}
audio.shutdown()
println('Done!')
}
fn audio_stream_callback(buffer &f32, num_frames int, num_channels int, user_data voidptr) {
mut data := unsafe { &AudioData(user_data) }
unsafe {
mut buf := buffer
total_samples := num_frames * num_channels
for i in 0 .. total_samples {
if data.pos >= data.samples.len {
buf[i] = 0.0
} else {
buf[i] = data.samples[data.pos]
data.pos++
}
}
}
}Only a Ogg decoder is present, so you may need to convert your song using ffmpeg ( |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
How do you play audio from a wav or mp3 file?
Beta Was this translation helpful? Give feedback.
All reactions