OStack程序员社区-中国程序员成长平台

标题: ios - 使用 AVAudioPlayer 从 URL 播放音频 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 18:48
标题: ios - 使用 AVAudioPlayer 从 URL 播放音频

我正在从下面给出的 URL 播放音频

"http://sumeetmusiclocal.wsisites.net/Songs/Kashyala Lavato (Lavani).mp3"

通过使用下面给出的代码

NSString *urlString = @"http://sumeetmusiclocal.wsisites.net/Songs/Kashyala Lavato (Lavani).mp3";
NSURL *audioFileLocationURL = [NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];

NSError *error;
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:audioFileLocationURL error:&error];
[audioPlayer setNumberOfLoops:-1];

if (error) {
    NSLog(@"%@", [error localizedDescription]);

    [[self volumeControl] setEnabled:NO];
    [[self playPauseButton] setEnabled:NO];

    [[self alertLabel] setText"Unable to load file"];
    [[self alertLabel] setHidden:NO];
} else {
    [[self alertLabel] setText:[NSString stringWithFormat"%@ has loaded", @"HeadspinLong.caf"]];
    [[self alertLabel] setHidden:NO];

    //Make sure the system follows our playback status
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
    [[AVAudioSession sharedInstance] setActive: YES error: nil];

    //Load the audio into memory
    [audioPlayer prepareToPlay];
}

但我收到错误提示

Printing description of error:
Error Domain=NSOSStatusErrorDomain Code=2003334207 "(null)"
2016-03-08 12:43:45.835 SumeetApp[1839:78581] The operation couldn’t be completed. (OSStatus error 2003334207.)

谁能帮我解决这个错误或建议我用其他方法从 url 播放音频。

谢谢



Best Answer-推荐答案


试试这个

AVURLAsset *asset = [AVURLAsset assetWithURL:[NSURL URLWithString"http://clips.vorwaerts-gmbh.de/VfE_html5.mp4"]];

AVPlayerItem *playerItem1 = [AVPlayerItem playerItemWithAsset:asset];
AVPlayer *player1 = [AVPlayer playerWithPlayerItem:playerItem1];
AVPlayerLayer *playerLayer1 = [AVPlayerLayer playerLayerWithPlayer:player1];
playerLayer1.videoGravity = AVLayerVideoGravityResizeAspectFill;
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
    playerLayer1.frame = self.view.frame;
});

[self.view.layer insertSublayer:playerLayer1 atIndex:1];
[player1 play];

希望这对你有用。

关于ios - 使用 AVAudioPlayer 从 URL 播放音频,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35861310/






欢迎光临 OStack程序员社区-中国程序员成长平台 (https://ostack.cn/) Powered by Discuz! X3.4