【问题标题】:Playing sound though http server iOS通过 http 服务器 iOS 播放声音
【发布时间】:2011-11-07 19:26:29
【问题描述】:

您好,我想通过我的服务器播放一个 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];

}

【问题讨论】:

  • 我认为你需要更清楚一点。我认为您是说您需要播放器工作,以便一次只能播放一种声音,但是您应该定义要发生的事情-声音是否应该排队播放一个接一个,是否应该忽略第二种声音而不是如果当前正在播放另一种声音时开始播放?
  • 我想用第二段代码创建会话,因为声音是同时播放的,这是我不想要的。我希望声音分开播放。因此,一旦你点击一个声音,它就会播放,一旦你点击另一个声音,前一个声音就会停止,另一个声音就会开始。使用 http mp3。

标签: iphone ios xcode cocoa-touch avplayer


【解决方案1】:

我的建议是将播放器的指针从在该方法中声明,以便在模块级别(在 .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。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多