Domanda

Is it possible to play a certain part of a .wav file in Python?

I'd like to have a function play(file, start, length) that plays the audiofile file from start seconds and stops playing after length seconds. Is this possible, and if so, what library do I need?

È stato utile?

Soluzione

this is possible and can be easy in python.

Pyaudio is a nice library and you can use to play your audio!

First do you need decode the audio file (wav, mp3, etc) this step convert audio data in numbers(short int or float32).

Do you need convert the seconds in equivalent position point to cut the signal in the position of interest, to do this multiply your frame rate by what seconds do you want !

Here one simple example for wav files:

import pyaudio
import sys
import numpy as np
import wave
import struct



File='ederwander.wav'
start = 12
length=7
chunk = 1024

spf = wave.open(File, 'rb')
signal = spf.readframes(-1)
signal = np.fromstring(signal, 'Int16')
p = pyaudio.PyAudio()

stream = p.open(format =
                p.get_format_from_width(spf.getsampwidth()),
                channels = spf.getnchannels(),
                rate = spf.getframerate(),
                output = True)


pos=spf.getframerate()*length

signal =signal[start*spf.getframerate():(start*spf.getframerate()) + pos]

sig=signal[1:chunk]

inc = 0;
data=0;


#play 
while data != '':
    data = struct.pack("%dh"%(len(sig)), *list(sig))    
    stream.write(data)
    inc=inc+chunk
    sig=signal[inc:inc+chunk]


stream.close()
p.terminate()

Altri suggerimenti

I know that this is a rather old question, but I just needed the exact same thing and for me ederwander's example seems a little bit too complicated.

Here is my shorter (and commented) solution:

import pyaudio
import wave

# set desired values
start = 7
length = 3

# open wave file
wave_file = wave.open('myWaveFile.wav', 'rb')

# initialize audio
py_audio = pyaudio.PyAudio()
stream = py_audio.open(format=py_audio.get_format_from_width(wave_file.getsampwidth()),
                       channels=wave_file.getnchannels(),
                       rate=wave_file.getframerate(),
                       output=True)

# skip unwanted frames
n_frames = int(start * wave_file.getframerate())
wave_file.setpos(n_frames)

# write desired frames to audio buffer
n_frames = int(length * wave_file.getframerate())
frames = wave_file.readframes(n_frames)
stream.write(frames)

# close and terminate everything properly
stream.close()
py_audio.terminate()
wave_file.close()
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top