如何创建像pandora app这样的audioplayer应用程序?

时间:2011-04-28 08:07:39

标签: iphone memory-management avaudioplayer

我创建了一个从本地播放多个音频文件的应用程序。音频文件很长。音频播放器具有以下用户选项

  • 转发,
  • 倒带,
  • 下一首曲目,
  • 上一曲,

我打算使用AvAudioPlayer,以便我可以长时间播放音频。当我更改音频文件,即按下一个音轨时。 audioplayer实例未被释放。此问题仅出现一些问题。请帮我..!!我帮少了..

下一曲目按钮IBAction方法

- (IBAction) nextTrackPressed
{
    [audioPlay stopAudio];
    if (audioPlay) {
        audioPlay = nil;
        [audioPlay release];
    }

    appDelegate.trackSelected += 1; 
    [self intiNewAudioFile];
    [self play];
}

Initializing audio file through below method

-(void) intiNewAudioFile
{
    NSAutoreleasePool *subPool = [[NSAutoreleasePool alloc] init];

    NSString *filePath = [[NSString alloc] init]; 

    trackObject = [appDelegate.trackDetailArray objectAtIndex:appDelegate.trackSelected];
    NSLog(@"%@",trackObject.trackName);
    // Get the file path to the song to play.
    filePath = [[NSBundle mainBundle] pathForResource:trackObject.trackName ofType:@"mp3"];

    // Convert the file path to a URL.
    NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:filePath];

    if (audioPlay) {
        audioPlay = nil;
        [audioPlay release];
    }

    audioPlay = [[AudioPlayerClass alloc] init];
    [audioPlay initAudioWithUrl:fileURL];

    [filePath release];
    [fileURL release];
    [subPool release];
}

AudioPlayerClass实施

#import "AudioPlayerClass.h"


@implementation AudioPlayerClass

- (void) initAudioWithUrl: (NSURL *) url
{

    curAudioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
    [curAudioPlayer setDelegate:self];
    [curAudioPlayer prepareToPlay];
}

- (void) playAudio
{
    [curAudioPlayer play];
}

- (void) pauseAudio
{
    [curAudioPlayer pause];
}

- (void) stopAudio
{
    [curAudioPlayer stop];
}

- (BOOL) isAudioPlaying
{
    return curAudioPlayer.playing;
}

- (void) setAudiowithCurrentTime:(NSInteger) time
{
    curAudioPlayer.currentTime = time;
}

- (NSInteger) getAudioFileDuration
{
    return curAudioPlayer.duration;
}

- (NSInteger) getAudioCurrentTime
{
    return curAudioPlayer.currentTime;
}

- (void) releasePlayer
{
    [curAudioPlayer release];
}

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

@end

1 个答案:

答案 0 :(得分:0)

你的问题在这里:

if (audioPlay) {
        audioPlay = nil;
        [audioPlay release];
    }

您在调用release之前将audioPlay设置为nil,这意味着释放消息将被发送到nil。你需要颠倒这两行的顺序。

if (audioPlay) {
        [audioPlay release];
         audioPlay = nil;
    }