Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

converting data to a numpy array #120

Open
gmabey opened this issue Mar 8, 2022 · 2 comments
Open

converting data to a numpy array #120

gmabey opened this issue Mar 8, 2022 · 2 comments

Comments

@gmabey
Copy link

gmabey commented Mar 8, 2022

The docs would be much more useful to me if this introductory sample

with audioread.audio_open(filename) as f:
    print(f.channels, f.samplerate, f.duration)
    for buf in f:
        do_something(buf)

included some notion of how to convert buf to a numpy array. If you have a minute. (and, if that's easy to do)

@sampsyo
Copy link
Member

sampsyo commented Mar 9, 2022

While I don't have a code snippet lying around, a good place to start would be numpy's built-in frombuffer method:
https://numpy.org/doc/stable/reference/generated/numpy.frombuffer.html

As you likely already know, audioread produces buffers containing 16-bit little-endian signed integers. So you'll want to invoke frombuffer with that number format.

@JustasB
Copy link

JustasB commented Mar 30, 2023

The following function will read a stereo file into numpy arrays:

import numpy as np
import audioread 

def audioread_load(path):
    result_audioread = []
    
    with audioread.audio_open(filename) as f:
        for i, buf in enumerate(f):
            result_audioread.append(np.frombuffer(buf, dtype=np.short))      
            
    result_audioread = np.concatenate(result_audioread)
    
    left_audioread = result_audioread[0::2]
    right_audioread = result_audioread[1::2]
    
    return left_audioread, right_audioread, f.samplerate

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants