gpt4 book ai didi

iphone - 从 URI 获取音频流并在 iPhone 上播放

转载 作者:技术小花猫 更新时间:2023-10-29 10:41:42 27 4
gpt4 key购买 nike

我想从 URL 获取音频流并在 iPhone 上播放。不幸的是,只有 C# 示例说明如何播放该流,但我需要在 iPhone 框架中实现 Objective C。我尝试过自己使用不同的音频框架,但都没有成功。这是 C# 中的内容:

response = httpWebRequest.GetResponse();
using (Stream stream = response.GetResponseStream())
{
using (SoundPlayer player = new SoundPlayer(stream))
{
player.PlaySync();
}
}

我应该在 objective-c 中做什么才能从该 url 获取流音频?在那个 URL 中我没有 mp3 文件或其他东西,我只是得到一个流。可能我必须以某种方式将该流下载到 iPhone 音频文件,然后播放它以消除延迟。

我试过这个:

 AVPlayer *player = [AVPlayer playerWithURL:url];
[player play];

还有这个:

AVAudioPlayer *theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL: url error:nil];

[theAudio setVolume :0.50]; //setting the volume

[theAudio play];

都没用。我已经测试了我的网址,它在浏览器中运行良好。

这是有效的代码:

NSData *_objectData = [NSData dataWithContentsOfURL:url];
NSError *error;

AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithData:_objectData error:&error];
audioPlayer.numberOfLoops = 0;
audioPlayer.volume = 1.0f;
[audioPlayer prepareToPlay];

if (audioPlayer == nil)
NSLog(@"%@", [error description]);
else
[audioPlayer play];

最佳答案

NSString* resourcePath = url; //your url
NSData *_objectData = [NSData dataWithContentsOfURL:[NSURL URLWithString:resourcePath]];
NSError *error;

app.audioPlayer = [[AVAudioPlayer alloc] initWithData:_objectData error:&error];
app.audioPlayer.numberOfLoops = 0;
app.audioPlayer.volume = 1.0f;
[app.audioPlayer prepareToPlay];

if (app.audioPlayer == nil)
NSLog(@"%@", [error description]);
else
[app.audioPlayer play];

关于iphone - 从 URI 获取音频流并在 iPhone 上播放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6856445/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com