通过http服务器iOS播放声音

时间:2011-11-07 19:26:29

标签: iphone ios xcode cocoa-touch avplayer

嗨我想通过我的服务器播放mp3文件,例如http://test.com/hi.mp3

当代码播放文件时,如果它在代码目录中。 该代码一次只能启用1个声音。

- (IBAction)oneSound:(id)sender; {
    NSString *path = [[NSBundle mainBundle] pathForResource:@"1" ofType:@"mp3"];
    if (theAudio) [theAudio release];
    NSError *error = nil;
    theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:&error];
    if (error)
        NSLog(@"%@",[error localizedDescription]);
    theAudio.delegate = self;
    [theAudio play];   


}

然而,这里的代码使我能够通过http服务器播放声音,但我可以一次播放多个声音,我需要会话中的声音,所以一次只能播放1个声音。我有10个声音。

- (IBAction)oneSound:(id)sender; {

    AVPlayer *player = [[AVPlayer playerWithURL:[NSURL URLWithString:@"http://www.mysite.com/hi.mp3"]] retain];

    [player play];

}

1 个答案:

答案 0 :(得分:0)

我的建议是移动播放器的指针,使其在该方法中声明,以便在模块级别(在.h文件中)声明 - 或者只是在接口中定义,或者定义为@property 。然后你可以在以后用另一种方法访问这个播放器。

然后,当您希望以其他方法切换到新声音时,您可以尝试:

[player pause];    // stop the player from playing
[player release];  // free the reference count
// start a new plaer
player = [[AVPlayer playerWithURL:
         [NSURL URLWithString:@"http://www.mysite.com/nextsound.mp3"]] retain];

你应该注意这里的'保留'电话。 playerWithURL将传回一个自动释放的对象,因此根据您在其他地方使用自动释放池所做的操作,并且根据您是否在其定义中使用包含(retain)的属性,您可能不需要在此处调用retain。

相关问题