2016-07-02 175 views
1

這是我的第一篇文章。播放過程中是否可以改變播放速度?我想模擬汽車發動機的聲音,爲此,第一步是根據發動機的轉速改變環狀樣品的速度。我知道如何通過改變波形文件的速率來增加使用pyaudio的完整樣本的速度,但我想要不斷改變速度。這可能沒有使用scikits.samplerate包,它允許重新採樣(並且是相當古老的)或pysonic,這是超級?Python:在播放過程中改變聲音的速度

這是我的時刻:

import pygame, sys 
import numpy as np 
import pyaudio 
import wave 
from pygame.locals import * 
import random as rd 
import os 
import time 

pygame.init() 

class AudioFile: 
    chunk = 1024 

    def __init__(self, file, speed): 
     """ Init audio stream """ 
     self.wf = wave.open(file, 'rb') 
     self.speed = speed 
     self.p = pyaudio.PyAudio() 
     self.stream = self.p.open(
      format = self.p.get_format_from_width(self.wf.getsampwidth()), 
      channels = 1, 
      rate = speed, 
      output = True) 

    def play(self): 
     """ Play entire file """ 
     data = self.wf.readframes(self.chunk) 
     while data != '': 
      self.stream.write(data) 

    def close(self): 
     """ Graceful shutdown """ 
     self.stream.close() 
     self.p.terminate() 

a = AudioFile("wave.wav") 
a.play() 
+0

是的可能,你是否可以改變速度,你的音高一起改變? – ederwander

回答

1

你應該能夠做一些與numpy的。我並不十分熟悉wave等,我期望你的play()方法以某種方式在循環中包含一個readframes()(正如我試圖在這裏做的那樣),但是你可能從這個

def play(self): 
    """ Play entire file """ 
    x0 = np.linspace(0.0, self.chunk - 1.0, self.chunk) 
    x1 = np.linspace(0.0, self.chunk - 1.0, self.chunk * self.factor) # i.e. 0.5 will play twice as fast 
    data = '' 
    while data != '': 
     f_data = np.fromstring(self.wf.readframes(self.chunk), 
           dtype=np.int).astype(np.float) # need to use floats for interpolation 
     if len(f_data) < self.chunk: 
      x1 = x1[:int(len(f_data) * self.factor)] 
     data = np.interp(x1, x0, f_data).astype(np.int) 
     self.stream.write(data) 

顯然,這對整個遊戲使用相同的加速或減速因子。如果你想在播放中改變它,你將不得不在while循環中修改x1。