PDA

View Full Version : Generating a DTMF tone doesn’t work - application crashes!




sagiftw
Aug 11, 2010, 07:14 AM
Hello,

I am trying to generate a pure DTMF tone that will be played by the iPhone.
In order to do so, I have created and allocated a memory buffer with a custom formula of the tone, then I created an object of type NSData, which is initialized with the memory buffer, and passed the NSData object to AVAudioPlayer.

I have also created 2 instance methods: "Play" and "Stop".
When the program loads, I press the "Play" button, and the program doesn't work.

This is the code of the program:



#import "AudioPlayerViewController.h"
#include <stdlib.h>
const int SIZE = 10;
const int LENGTH = 65535;
const int PLAYBACKFREQ = 44100;
const float PI2 = 3.14159265359f * 2;
const int freq1 = 697;
const int freq2 = 1209;


@implementation AudioPlayerViewController

@synthesize playButton, stopButton;

- (void)viewDidLoad {
[super viewDidLoad];
// NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/music1.mp3", [[NSBundle mainBundle] resourcePath]]];
//audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];


// Allocate space for an array with ten elements of type int.
int *ptr = malloc(SIZE * sizeof(int));
if (ptr == NULL) NSLog(@"Error: Memory buffer could not be allocated.");

for(int i=0; i<SIZE; i++) ptr[i] = (sin(i*(PI2*(PLAYBACKFREQ/freq1))) + sin(i*(PI2*(PLAYBACKFREQ/freq2)))) * 16383;
NSData *myData = [[NSData alloc] initWithBytes:ptr length:SIZE];
//free(ptr);
//ptr = NULL;



audioPlayer = [[AVAudioPlayer alloc] initWithData:myData error:&error];
audioPlayer.numberOfLoops = -1;
}

-(IBAction) playAudio: (id) sender {
if (audioPlayer == nil) NSLog([error description]);
else [audioPlayer play];
}

-(IBAction) stopAudio: (id) sender { [audioPlayer stop]; }

- (void)dealloc {
[audioPlayer release];
[super dealloc];
}

@end




Please help me - any kind of help will be appreciated!

Thanks in advance,

Sagiftw;)



chown33
Aug 11, 2010, 10:07 AM
1. You are generating sampled audio as pure int samples (PCM at sizeof(int)). Is that an audio format that AVAudioPlayer can understand? If you don't know what an audio format is, see the AVAudioPlayer reference docs and look at CAF, AIF, MP3, etc.
http://en.wikipedia.org/wiki/Audio_file_format
http://en.wikipedia.org/wiki/Core_Audio_Format

2. In this line of code:
NSData *myData = [[NSData alloc] initWithBytes:ptr length:SIZE];

You are telling NSData that the byte-count is SIZE. Is this appropriate for a buffer containing SIZE ints?

3. After you address the above, re-examine your fundamental design. How many cycles of a 697 Hz audio signal will fit in a buffer containing SIZE samples, where SIZE is 10? If you have less than a complete cycle, is that a sufficiently accurate representation of the audio?