繁体   English   中英

如何在iPhone Objective-C中使用AVAudioPlayer播放URL链接的音频文件

[英]How to play audio file of URL link using AVAudioPlayer in iphone objective-c

我正在我的应用程序中创建语音通信功能,该功能通过Web服务器在用户之间发送语音注释,但是在测试过程中,播放用AVAudioPlayer创建的消息时遇到错误。 AVAudioplayer仅返回一个值。

如何使用AVAudioPlayerURL链接播放音频文件?

if (!self.audioRecorder.recording) {

        NSURL *url = [NSURL URLWithString:[@"http://.../sound.mp4"]];
        NSLog(@"%@", url);
        NSLog(@"PlayBack");

        NSData *audioData = [NSData dataWithContentsOfURL:url];
        NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                                   NSUserDomainMask, YES) objectAtIndex:0]
                              stringByAppendingPathComponent:@"sound1.caf"];
        [audioData writeToFile:filePath atomically:YES];


        NSError *error;
        NSURL *fileURL = [NSURL fileURLWithPath:filePath];
        self.audioPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:fileURL error:&error];
        if (self.audioPlayer == nil) {
            NSLog(@"%@", [error description]);
            NSLog(@"%@", [self.audioPlayer description]);
        }else
            [self.audioPlayer play];
    }else [self.audioRecorder stop];

请尝试以下代码:

- (void) playMessageSound : (NSString *) filename{

self.soundFilename = filename;
//[[RBDMuteSwitch sharedInstance] detectMuteSwitch];
NSString *name = [filename stringByDeletingPathExtension];
NSString *extension = [filename pathExtension];
NSString *filePath = [[NSBundle mainBundle]pathForResource:name ofType:extension];
NSURL *fileUrl = [NSURL fileURLWithPath:filePath];
NSError *error;
self.audioPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:fileUrl error:&error];
self.audioPlayer.numberOfLoops = 0;
self.audioPlayer.volume = 1.0;
[self.audioPlayer play];

}

检查这个

 NSString* resourcePath = @""; //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 = 4.0f;
        [app.audioPlayer prepareToPlay];

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM