生成DTMF音不起作用-应用程序崩溃! [英] Generating a DTMF tone doesn't work - application crashes!
问题描述
我想生成自定义的DTMF音并在iPhone上播放. 为了做到这一点,我创建并分配了带有自定义音调(ptr)的内存缓冲区. 现在,我想创建一个使用内存缓冲区初始化的NSData对象,然后使用initWithData:error:实例方法将其传递给AVAudioPlayer.
I want to generate a custom DTMF tone and play it on the iPhone. In order to do so, I have created and allocated a memory buffer with a custom tone (ptr). Now I want to create a NSData object, initialized with the memory buffer, and pass it to AVAudioPlayer using initWithData:error: instance method.
我编写了以下代码,但是当我运行应用程序时,它崩溃了.
I wrote the following code, but when I run my application, it crashes.
#import "AudioPlayerViewController.h"
#include <stdlib.h>
#include <math.h>
#define SIZE 10
#define 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];
// 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.");
else NSLog(@"Allocation succeeded.");
// The formula for the tone, the content of the buffer.
for(int i=0; i<SIZE; i++) ptr[i] = (sin(i*(PI2*(PLAYBACKFREQ/freq1))) + sin(i* (PI2*(PLAYBACKFREQ/freq2)))) * 16383;
NSData *myData = [[NSData alloc] initWithBytesNoCopy: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];
[myData release];
[super dealloc];
}
@end
在文档中,方法initWithBytesNoCopy的描述为:
In the documentation, the description of method initWithBytesNoCopy reads:
包含新对象数据的缓冲区.字节必须指向使用malloc分配的内存块."
"A buffer containing data for the new object. bytes must point to a memory block allocated with malloc."
所以我已经做到了,但是没用.
So I have already done this, but it doesn't work.
任何帮助将不胜感激!
预先感谢
Sagiftw
推荐答案
您正在按SIZE进行分配,但传入LENGTH作为长度.您已将SIZE定义为"10",并将LENGTH定义为一个巨大的数字.难怪它会在您分配的区域末尾消失!
You're mallocing by SIZE but passing in LENGTH as the length. You've defined SIZE as "10" and LENGTH as a huge number. It's no wonder it goes way mast the end of the region you malloced!
这篇关于生成DTMF音不起作用-应用程序崩溃!的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!