0
我想生成一個自定義DTMF音調並在iPhone上播放。 爲了做到這一點,我創建並分配了一個自定義音調(ptr)的內存緩衝區。 現在我想創建一個NSData對象,用內存緩衝區初始化,並使用initWithData:error:instance方法將它傳遞給AVAudioPlayer。生成DTMF音色不起作用 - 應用程序崩潰!
我寫了下面的代碼,但是當我運行我的應用程序時,它崩潰了。
#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
好的,你說得對。 我將它改爲SIZE,現在應用程序加載,但是當我按下「播放」按鈕時,它會崩潰。 – Sagiftw 2010-08-11 08:34:04