| package sound |
|
|
| import ( |
| "encoding/binary" |
| "math" |
| ) |
|
|
| |
| |
| |
| |
| |
| |
| |
|
|
| |
| func CalculateRMS16(buffer []int16) float64 { |
| var sumSquares float64 |
| for _, sample := range buffer { |
| val := float64(sample) |
| sumSquares += val * val |
| } |
| meanSquares := sumSquares / float64(len(buffer)) |
| return math.Sqrt(meanSquares) |
| } |
|
|
| func ResampleInt16(input []int16, inputRate, outputRate int) []int16 { |
| |
| ratio := float64(inputRate) / float64(outputRate) |
|
|
| |
| outputLength := int(float64(len(input)) / ratio) |
|
|
| |
| output := make([]int16, outputLength) |
|
|
| |
| for i := 0; i < outputLength-1; i++ { |
| |
| pos := float64(i) * ratio |
|
|
| |
| indexBefore := int(pos) |
| indexAfter := indexBefore + 1 |
| if indexAfter >= len(input) { |
| indexAfter = len(input) - 1 |
| } |
|
|
| |
| frac := pos - float64(indexBefore) |
|
|
| |
| output[i] = int16((1-frac)*float64(input[indexBefore]) + frac*float64(input[indexAfter])) |
| } |
|
|
| |
| output[outputLength-1] = input[len(input)-1] |
|
|
| return output |
| } |
|
|
| func ConvertInt16ToInt(input []int16) []int { |
| output := make([]int, len(input)) |
| for i, value := range input { |
| output[i] = int(value) |
| } |
| return output |
| } |
|
|
| func BytesToInt16sLE(bytes []byte) []int16 { |
| |
| if len(bytes)%2 != 0 { |
| panic("bytesToInt16sLE: input bytes slice has odd length, must be even") |
| } |
|
|
| int16s := make([]int16, len(bytes)/2) |
| for i := 0; i < len(int16s); i++ { |
| int16s[i] = int16(bytes[2*i]) | int16(bytes[2*i+1])<<8 |
| } |
| return int16s |
| } |
|
|
| func Int16toBytesLE(arr []int16) []byte { |
| le := binary.LittleEndian |
| result := make([]byte, 0, 2*len(arr)) |
| for _, val := range arr { |
| result = le.AppendUint16(result, uint16(val)) |
| } |
| return result |
| } |
|
|