gpt4 book ai didi

ios - 在iOS中从Internet下载的音频文件无法播放

转载 作者:行者123 更新时间:2023-12-01 17:32:00 25 4
gpt4 key购买 nike

好吧,我已经阅读了很多类似的问题,但是我仍然无法解决问题。

我将从互联网上下载音频文件,然后播放它们。使用NSURLConnection,我成功下载了文件。这是我下载文件的代码。

- (IBAction)download:(id)sender 
{
NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.dailywav.com/0813/bicycles.wav"]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];

if (theConnection) {
receivedData = [NSMutableData data] ;
} else {NSLog(@"no connection!");
}

然后为了保存和播放文件,我编写了以下内容
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{

[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;

NSLog(@"didfinishloading Received %d bytes of data",[receivedData length]);

NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES);
NSLog(@"%@", [documentPaths objectAtIndex:0]);
NSString *documentDirectoryPath = [documentPaths objectAtIndex:0];
NSString *folderPath = [documentDirectoryPath stringByAppendingPathComponent:@"myFolder/doScience.wav"];
[receivedData writeToFile:folderPath atomically:YES];
NSError *error;
AVPlayer * player = [[AVPlayer alloc]initWithURL:[NSURL URLWithString:folderPath]];
if (player == nil) {
NSLog(@"AudioPlayer did not load properly: %@", [error description]);
} else {
[player play];
NSLog(@"playing!");
}
}

这是我运行后从控制台获得的信息

2013-08-23 13:57:51.636下载_2 [4461:c07] didfinishloading收到
34512字节的数据2013-08-23 13:57:51.637下载_2 [4461:c07]
/ Users / my_name / Library / Application Support / iPhone
模拟器/6.1/应用程序/ 88561BAC-66BF-4774-A626-0CEFEC82D63E /库/文档
2013-08-23 13:57:51.639下载_2 [4461:c07]玩!

似乎一切正常,但是问题是我在运行项目时听不到任何声音!

最佳答案

播放远程文件的方法更简单-使用AVPlayer而不是AVAudioPlayer。由于AVPlayer可以在下载过程中播放文件,因此它也更加用户友好。

- (IBAction)playSound:(UIButton *)sender
{
NSURL *url = [[NSURL alloc] initWithString:@"http://www.dailywav.com/0813/bicycles.wav"];
AVAsset *asset = [AVURLAsset URLAssetWithURL:url options:nil];
AVPlayerItem *anItem = [AVPlayerItem playerItemWithAsset:asset];

player = [AVPlayer playerWithPlayerItem:anItem];
[player addObserver:self forKeyPath:@"status" options:0 context:nil];
}


- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{

if (object == player && [keyPath isEqualToString:@"status"]) {
if ([player status] == AVPlayerStatusFailed) {
NSLog(@"AVPlayer Failed");
} else if ([player status] == AVPlayerStatusReadyToPlay) {
NSLog(@"AVPlayer Ready to Play");
[player play];
} else if ([player status] == AVPlayerItemStatusUnknown) {
NSLog(@"AVPlayer Unknown");
}
}
}

您还可以找到示例项目 here

关于ios - 在iOS中从Internet下载的音频文件无法播放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18357702/

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