【问题标题】:Generating a DTMF tone doesn't work - application crashes!生成 DTMF 音不起作用 - 应用程序崩溃!
【发布时间】:2010-08-11 16:34:17
【问题描述】:

我想生成自定义 DTMF 音并在 iPhone 上播放。 为此,我创建并分配了一个带有自定义音调 (ptr) 的内存缓冲区。 现在我想创建一个 NSData 对象,使用内存缓冲区进行初始化,然后使用 initWithData:error: 实例方法将其传递给 AVAudioPlayer。

我编写了以下代码,但是当我运行我的应用程序时,它崩溃了。

#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 的描述如下:

“包含新对象数据的缓冲区。字节必须指向使用 malloc 分配的内存块。”

所以我已经这样做了,但是它不起作用。

任何形式的帮助将不胜感激!

提前致谢,

Sagiftw

【问题讨论】:

    标签: iphone objective-c buffer avaudioplayer nsdata


    【解决方案1】:

    您按 SIZE 进行分配,但将 LENGTH 作为长度传递。您已将 SIZE 定义为“10”,将 LENGTH 定义为一个巨大的数字。难怪它会在你分配的区域的尽头出现!

    【讨论】:

    • 好吧,你说得对。我将其更改为 SIZE,现在应用程序已加载,但当我按下“播放”按钮时,它崩溃了。
    猜你喜欢
    • 2010-11-26
    • 2018-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多