通过http服务器iOS播放声音



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

此时,如果该文件在代码的目录中,代码将播放该文件。代码还允许一次只发出一个声音。

- (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];
}

我的建议是移动播放器的指针,使其在模块级别(在.h文件中)声明-要么只是在接口中定义,要么定义为@属性。然后,您可以稍后以另一种方法访问此播放器。

当你想用另一种方法切换到新的声音时,你可以尝试:

[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];

你应该小心这里的'retain'调用。playerWithURL将传递回一个自动释放对象,所以取决于你在其他地方使用自动释放池做什么,取决于你是否在其定义中使用包含(retain)的属性,你可能不需要在这里调用retain。

最新更新