Go Down

Topic: Success getting TMRpcm to change the pitch and speed of sounds (Read 250 times) previous topic - next topic

Ozerik

Thanks to an old post here I inserted some code into the TMRpcm library, and getting it to play clips with a variable speed and pitch by changing the sample rate for each time the sound file is played.

In file TRMpcm.cpp I changed these two lines:

Code: [Select]

    SAMPLE_RATE = sFile.read();
    SAMPLE_RATE = sFile.read() << 8 | SAMPLE_RATE;


to these four lines of code:

Code: [Select]


    SAMPLE_RATE = sFile.read();  // you need these two reads just to make sure that
    SAMPLE_RATE = sFile.read();  //  the file pointer is in the right place for later code
    int pot = analogRead(A0);      // or what ever the pot is on
    SAMPLE_RATE = map(pot, 0, 1023, 8000, 44000);



It works PERFECTLY!!! Problem: the sample rate and therefore pitch/speed are only changed at the beginning of each playback event, which is no biggie for my project. But if I wanted to change the sample rate mid-playback, how..... how would I do that???

Grumpy_Mike

Quote
But if I wanted to change the sample rate mid-playback,
Can you explain what you mean by that, that has me confused.

Ozerik

Can you explain what you mean by that, that has me confused.
Sure, I want pitch/speed (basically, the sample playback rate) to change in the middle of playing a sound. At the moment, it only detects the sample rate when the clip starts to be played.

Grumpy_Mike

Not sure you can do that. As it would mean receiving MIDI messages while you are outputting the samples. When you do that what you are producing will glitch as you will interfere with the sample rate.

Lucario448

I think this is how (assuming you're using a 16-bit timer):

Code: [Select]
unsigned long newSR = map(analogRead(A0), 0, 1023, 8000, 44100);

if (bitRead(optionByte,6)) *ICRn[tt] = 10 * (800000 /  newSR);
else *ICRn[tt] = 10 * (1600000 / newSR);

optionByte and ICRn are actually global variables, so there should be no problem in using them anywhere (at compiling time though); furthermore no library modification required.
Although not sure if there would be a side effect since this also changes PWM's (carrier) frequency, and if the duty cycle (outputted sample's value) will be scaled accordingly.

Go Up