wavy

package module
v1.20.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 22, 2022 License: MIT Imports: 12 Imported by: 1 module, 1 package

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

wavy

Wavy is a high-level, easy to use, and cross-platform Go sound library built on top of https://github.com/hajimehoshi/oto.

Wavy supports both streaming sounds from disk and playing from memory.

Supported Platforms

Supported platforms are:

  • Windows
  • macOS
  • Linux
  • FreeBSD
  • OpenBSD
  • Android
  • iOS
  • WebAssembly

If you are using iOS or Linux please check this.

Supported audio formats

  • MP3 (.mp3)
  • Wav (.wav/.wave)
  • OGG (.ogg)

Usage

Installation

First install Wavy with go get github.com/bloeys/wavy, and if you are using iOS or Linux check this.

Basics

You can start playing sounds with a few lines:

import (
    "github.com/bloeys/wavy"
)

func main() {

    //At the start if your program you should init wavy and tell it the
    //sampling rate of your sounds (usually 44100), the number of 
    //channels (usually 2) and the number of bytes per channel (usually 2).
    //
    //These settings will be used for all sounds regardless of their actual settings
    err := wavy.Init(wavy.SampleRate_44100, wavy.SoundChannelCount_2, wavy.SoundBitDepth_2)
    if err != nil {
        panic("Failed to init wavy. Err: " + err.Error())
    }

    //Here we load a sound into memory
    mySound, err := wavy.NewSoundMem("./my-sound.mp3")
    if err != nil {
        panic("Failed to create new sound. Err: " + err.Error())
    }

    //Now we set volume of this sound to 50% then play the sound
    //and wait for it to finish (PlayAsync plays in the background)
    mySound.SetVolume(0.5)
    mySound.PlaySync()

    //Since the sound finished playing, lets reset to start
    //by seeking to 0% then play again. Seeking to 0.5 then playing
    //will start from the middle the sound.
    mySound.SeekToPercent(0)
    mySound.PlayAsync()

    //The sound is playing the background, so lets wait for it to finish
    mySound.Wait()
}

If you are dealing with large sound files you might want to stream from a file (play as you go), this will only use a small amount of memory, but is less flexible and might be slower to seek.

Here is an example streaming a sound:


    //Here we load a sound into memory
    mySound, err := wavy.NewSoundStreaming("./my-sound.mp3")
    if err != nil {
        panic("Failed to create new sound. Err: " + err.Error())
    }

    //Rest is the same...
Controls

Once you have loaded a sound you can:

  • Pause/Resume
  • Set volume per sound
  • Play synchronously or asynchronously
  • Loop a number of times or infinitely
  • Check total play time and remaining time
  • Seek to any position (by percent or time) of the sound even when its already playing
  • Wait for a sound to finish playing once
  • Wait for a looping sound to finish all its repeats
  • (only in-memory) Load it once but have many versions play from different positions simultaneously (e.g. one gun starting to shoot, another ending its shot sound)
  • (only in-memory) Take a short clip from a sound (e.g. keep only the first half of the sound)

Code examples of everything:


//Load wav into memory
mySound, err := wavy.NewSoundMem("./my-sound.wav")
if err != nil {
    panic("Failed to create new sound. Err: " + err.Error())
}

//Play for ~1s then Pause
mySound.PlayAsync()
time.sleep(1 * time.Second)
mySound.Pause()

//Resume and play till end
mySound.PlaySync()

//Set volume to 25%
mySound.SetVolume(0.25)

//Play the sound three times and wait for all 3 plays to finish.
//Negative numbers will play infinitely till paused
mySound.LoopAsync(3)
mySound.WaitLoop()

//Check playtime
println("Time to play full sound:", mySound.TotalTime().Seconds())
println("Time remaining till sound finishes:", mySound.RemainingTime().Seconds())

//Play sound from the middle
mySound.SeekToPercent(0.5)
mySound.PlaySync()

//Play sound from time=5s
mySound.SeekToTime(5 * time.Second)
mySound.PlaySync()

//Wait for sound to finish if started async
mySound.Wait()

//Start looping infinitely then stop
mySound.LoopAsync(-1)
time.Sleep(1 * time.Second)
mySound.Pause()

//
// Things only possible for in-memory sounds
//

//1. Playing sound many times simultaneously without loading it multiple times

//We reuse the underlying sound data but get two independent sounds with their own controls!
//This operation is fast so you can do it a lot
mySound2 := CopyInMemSound(mySound)

//Set one to play from the beginning and the other to play from the middle
mySound.SeekToPercent(0)
mySound2.SeekToPercent(0.5)

//Play both simultaneously
mySound.PlayAsync()
mySound2.PlayAsync()

//Wait for both to finish
mySound.Wait()
mySound2.Wait()

//2. Cut parts of a sound

//Here we get a new sound that only has the first half of the sound.
//This operation is very quick and does not duplicate the underlying data
clippedSound := ClipInMemSoundPercent(mySound, 0, 0.5)
clippedSound.PlaySync()

Aside from per sound controls, there are a few global controls:

wavy.PauseAllSounds()
wavy.ResumeAllSounds()

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrInvalidWhence   = errors.New("invalid whence value. Must be: io.SeekStart, io.SeekCurrent, or io.SeekEnd")
	ErrNegativeSeekPos = errors.New("negative seeker position")
)

Pre-defined errors

View Source
var (
	Ctx *oto.Context

	SamplingRate SampleRate
	ChanCount    SoundChannelCount
	BitDepth     SoundBitDepth

	BytesPerSample int64
	BytesPerSecond int64
)

Those values are set after Init

Functions

func ByteCountFromPlayTime

func ByteCountFromPlayTime(t time.Duration) int64

PlayTimeFromByteCount returns how many bytes are needed to produce a sound that takes t time to play

func F32ToUnsignedPCM16 added in v1.11.0

func F32ToUnsignedPCM16(fs []float32, outBuf []byte) []byte

F32ToUnsignedPCM16 takes PCM data stored as float32 between [-1, 1] and returns a byte array of uint16, where each two subsequent bytes represent one uint16.

func Init

func Init(sr SampleRate, chanCount SoundChannelCount, bitDepth SoundBitDepth) error

Init prepares the default audio device and does any required setup. It must be called before loading any sounds

func PauseAllSounds

func PauseAllSounds()

func PlayTimeFromByteCount

func PlayTimeFromByteCount(byteCount int64) time.Duration

PlayTimeFromByteCount returns the time taken to play this many bytes

func ReadAllFromReader

func ReadAllFromReader(reader io.Reader, readingBufSize, ouputBufSize uint64) ([]byte, error)

ReadAllFromReader takes an io.Reader and reads until error or io.EOF.

If io.EOF is reached then read bytes are returned with a nil error. If the reader returns an error that's not io.EOF then everything read till that point is returned along with the error

readingBufSize is the buffer used to read from reader.Read(). Bigger values might read more efficiently. If readingBufSize<4096 then readingBufSize is set to 4096

ouputBufSize is used to set the capacity of the final buffer to be returned. This can greatly improve performance if you know the size of the output. It is allowed to have an outputBufSize that's smaller or larger than what the reader ends up returning

func ResumeAllSounds

func ResumeAllSounds()

Types

type OggStreamer added in v1.12.0

type OggStreamer struct {
	F   *os.File
	Dec *oggvorbis.Reader
}

func NewOggStreamer added in v1.12.0

func NewOggStreamer(f *os.File, dec *oggvorbis.Reader) *OggStreamer

func (*OggStreamer) Read added in v1.12.0

func (ws *OggStreamer) Read(outBuf []byte) (floatsRead int, err error)

func (*OggStreamer) Seek added in v1.12.0

func (ws *OggStreamer) Seek(offset int64, whence int) (int64, error)

func (*OggStreamer) Size added in v1.12.0

func (ws *OggStreamer) Size() int64

Size returns number of bytes

type SampleRate

type SampleRate int
const (
	SampleRate_44100 SampleRate = 44100
	SampleRate_48000 SampleRate = 48000
)

type Sound

type Sound struct {
	Player       oto.Player
	PlayerSeeker io.Seeker
	Info         SoundInfo

	// File is the file descriptor of the sound file being streamed.
	// This is only set if sound is streamed, and is kept to ensure GC doesn't hit it
	File *os.File

	// Data is an io.ReadSeeker over an open file or over a buffer containing the uncompressed sound file.
	// Becomes nil after close
	Data io.ReadSeeker

	IsLooping bool
}

func ClipInMemSoundPercent

func ClipInMemSoundPercent(s *Sound, fromPercent, toPercent float64) *Sound

ClipInMemSoundPercent is like CopyInMemSound but produces a sound that plays only between from and to. fromPercent and toPercent must be between 0 and 1

func CopyInMemSound

func CopyInMemSound(s *Sound) *Sound

CopyInMemSound returns a new sound object that has identitcal info and uses the same underlying data, but with independent play controls (e.g. one playing at the start while one is in the middle). Since the sound data is not copied this function is very fast.

Panics if the sound is not in-memory

func NewSoundMem

func NewSoundMem(fpath string) (s *Sound, err error)

NewSoundMem loads the entire sound file into memory

func NewSoundStreaming

func NewSoundStreaming(fpath string) (s *Sound, err error)

NewSoundStreaming plays sound by streaming from a file, so no need to load the entire file into memory. Good for large sound files

func (*Sound) Close

func (s *Sound) Close() error

Close will clean underlying resources, and the 'Ctx' and 'Bytes' fields will be made nil. Repeated calls are no-ops

func (*Sound) IsClosed

func (s *Sound) IsClosed() bool

func (*Sound) IsPlaying

func (s *Sound) IsPlaying() bool

func (*Sound) LoopAsync

func (s *Sound) LoopAsync(timesToPlay int)

LoopAsync plays the sound 'timesToPlay' times. If timesToPlay<0 then it is played indefinitely until paused If timesToPlay==0 then the sound is not played. If a sound is already playing then it will be paused then resumed in a looping manner

func (*Sound) Pause

func (s *Sound) Pause()

func (*Sound) PlayAsync

func (s *Sound) PlayAsync()

PlayAsync plays the sound in the background and returns.

func (*Sound) PlaySync

func (s *Sound) PlaySync()

PlaySync calls PlayAsync() followed by Wait()

func (*Sound) RemainingTime

func (s *Sound) RemainingTime() time.Duration

RemainingTime returns the time left in the clip, which is affected by pausing/resetting/seeking of the sound. Returns zero after close

func (*Sound) SeekToPercent

func (s *Sound) SeekToPercent(percent float64)

SeekToPercent moves the current position of the sound to the given percentage of the total sound length. For example, if a sound is 10s long and percent=0.5 then when the sound is played it will start from 5s.

This can be used while the sound is playing.

percent is clamped [0,1], so passing <0 is the same as zero, and >1 is the same as 1

func (*Sound) SeekToTime

func (s *Sound) SeekToTime(t time.Duration)

SeekToTime moves the current position of the sound to the given duration. For example if you use t=5*time.Second then play you will start from 5th second.

This can be used while the sound is playing.

t is clamped between [0, totalTime]

func (*Sound) SetVolume

func (s *Sound) SetVolume(newVol float64)

SetVolume must be between 0 and 1 (both inclusive). Other values will panic. The default volume is 1.

func (*Sound) TotalTime

func (s *Sound) TotalTime() time.Duration

TotalTime returns the time taken to play the entire sound. Safe to use after close

func (*Sound) Volume

func (s *Sound) Volume() float64

Volume returns the current volume

func (*Sound) Wait

func (s *Sound) Wait()

Wait blocks until sound finishes playing. If the sound is not playing Wait returns immediately. In the worst case (Wait sleeping then sound immediately paused), Wait will block ~4% of the total play time. In most other cases Wait should be accurate to ~1ms.

If you want to wait for all loops to finish then use WaitLoop

func (*Sound) WaitLoop

func (s *Sound) WaitLoop()

WaitLoop waits until the sound is no longer looping

type SoundBitDepth

type SoundBitDepth int
const (
	SoundBitDepth_1 SoundBitDepth = 1
	SoundBitDepth_2 SoundBitDepth = 2
)

type SoundBuffer

type SoundBuffer struct {
	Data []byte

	// Pos is the starting position of the next read
	Pos int64
}

func (*SoundBuffer) Copy

func (sb *SoundBuffer) Copy() *SoundBuffer

Copy returns a new SoundBuffer that uses the same `Data` but with an independent ReadSeeker. This allows you to have many readers all reading from different positions of the same buffer.

The new buffer will have its starting position set to io.SeekStart (`Pos=0`)

func (*SoundBuffer) Read

func (sb *SoundBuffer) Read(outBuf []byte) (bytesRead int, err error)

Read only returns io.EOF when bytesRead==0 and no more input is available

func (*SoundBuffer) Seek

func (sb *SoundBuffer) Seek(offset int64, whence int) (int64, error)

Seek returns the new position. An error is only returned if the whence is invalid or if the resulting position is negative.

If the resulting position is >=len(SoundBuffer.Data) then future Read() calls will return io.EOF

type SoundChannelCount

type SoundChannelCount int
const (
	SoundChannelCount_1 SoundChannelCount = 1
	SoundChannelCount_2 SoundChannelCount = 2
)

type SoundInfo

type SoundInfo struct {
	Type SoundType
	Mode SoundMode

	Size int64
}

SoundInfo contains static info about a loaded sound file

type SoundMode

type SoundMode int
const (
	SoundMode_Streaming SoundMode = iota
	SoundMode_Memory
)

type SoundType

type SoundType int
const (
	SoundType_Unknown SoundType = iota
	SoundType_MP3
	SoundType_WAV
	SoundType_OGG
)

func GetSoundFileType

func GetSoundFileType(fpath string) SoundType

type WavStreamer added in v1.12.0

type WavStreamer struct {
	F        *os.File
	Dec      *wav.Decoder
	Pos      int64
	PCMStart int64
}

func NewWavStreamer added in v1.12.0

func NewWavStreamer(f *os.File, wavDec *wav.Decoder) (*WavStreamer, error)

func (*WavStreamer) Read added in v1.12.0

func (ws *WavStreamer) Read(outBuf []byte) (bytesRead int, err error)

func (*WavStreamer) Seek added in v1.12.0

func (ws *WavStreamer) Seek(offset int64, whence int) (int64, error)

func (*WavStreamer) Size added in v1.12.0

func (ws *WavStreamer) Size() int64

Size returns number of bytes

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址