如何让我的两个音频播放器同时播放两首不同的歌曲?

Posted

技术标签:

【中文标题】如何让我的两个音频播放器同时播放两首不同的歌曲?【英文标题】:How do I get my two audioplayers to play two different songs simultaneously? 【发布时间】:2016-04-10 06:50:04 【问题描述】:

好的,我会尽力解释这一点。我的应用程序有两个音频播放器,我希望能够从我的音乐库中播放每个播放器的歌曲。我遇到的问题是,当我选择第一首歌曲播放时,它会起作用,然后当我选择另一首歌曲时,它会关闭第一首歌曲,并且两个音频播放器只能播放选择的歌曲。如何让音频播放器播放两首不同的歌曲?这是我目前的代码:

 //EDITED CODE: 
class GameScene: SKScene, MPMediaPickerControllerDelegate, AVAudioPlayerDelegate 

var mediaPicker: MPMediaPickerController?
var mediaPicker2: MPMediaPickerController?

var music2 = MPMediaItem()
var music = MPMediaItem()

var musicPlayer2 = AVAudioPlayer()
var musicPlayer = AVAudioPlayer()


func mediaPicker(mediaPicker: MPMediaPickerController, didPickMediaItems mediaItemCollection: MPMediaItemCollection) 
mediaPicker.dismissViewControllerAnimated(true, completion: nil)

let aMediaItem = mediaItemCollection.items[0] as MPMediaItem
music = aMediaItem
NSLog("\(aMediaItem.title)selected")


let url: NSURL = (music.valueForProperty(MPMediaItemPropertyAssetURL) as? NSURL)!

    do 
        musicPlayer = try AVAudioPlayer(contentsOfURL: url)

     catch 
        return
    
        musicPlayer.pause()
        leftPlayButton.hidden = false




if mediaItemCollection.items.count > 1 
    let aMediaItem2 = mediaItemCollection.items[1] as MPMediaItem
    music2 = aMediaItem2

    let url2: NSURL = (music2.valueForProperty(MPMediaItemPropertyAssetURL) as? NSURL)!

    do 
        musicPlayer2 = try AVAudioPlayer(contentsOfURL: url2)

     catch 
        return
    
    musicPlayer2.pause()
    rightPlayButton.hidden = false


 
            if node.name == "addmusictoleft" 
            mediaPicker = MPMediaPickerController(mediaTypes: .Music)

            if let picker2 = mediaPicker


                print("Successfully open media picker Left")
                picker2.delegate = self
                picker2.allowsPickingMultipleItems = true
                picker2.showsCloudItems = false
                picker2.prompt = "Pick a song for left player"
                self.view?.window?.rootViewController!.presentViewController(picker2, animated: true, completion: nil)

             else 
                print("PICKER WONT OPEN")
            
        


            if node.name == "addmusictoright" 
            mediaPicker2 = MPMediaPickerController(mediaTypes: .Music)
            if let picker = mediaPicker2


                print("Successfully open media picker Right")
                picker.delegate = self
                picker.allowsPickingMultipleItems = false
                picker.showsCloudItems = false
                picker.prompt = "Pick a song for right player"
                self.view?.window?.rootViewController!.presentViewController(picker, animated: true, completion: nil)

             else 
                print("PICKER WONT OPEN")
            



        

【问题讨论】:

【参考方案1】:

我制作了演示项目,它在我的 iPad 上运行良好。 这是我的代码。

ViewController.h

#import <UIKit/UIKit.h>
#import <MediaPlayer/MediaPlayer.h>
#import <AVFoundation/AVFoundation.h>

@interface ViewController : UIViewController<MPMediaPickerControllerDelegate,AVAudioPlayerDelegate>


@end

ViewController.m

#import "ViewController.h"


@interface ViewController ()

int counter;



@property AVAudioPlayer *avAudioPlayer;
@property AVAudioPlayer *avAudioPlayer2;

@end

@implementation ViewController 

- (void)viewDidLoad 

[super viewDidLoad];


counter = 0;
self.avAudioPlayer.delegate = self;
self.avAudioPlayer2.delegate = self;

UIButton *button1 = [[UIButton alloc]initWithFrame:CGRectMake(120, 50, 80, 30)];
[button1 addTarget:self action:@selector(button1Click:) forControlEvents:UIControlEventTouchUpInside];
button1.backgroundColor = [UIColor yellowColor];
[button1 setTitle:@"play" forState:UIControlStateNormal];
[self.view addSubview:button1];


UIButton *button2 = [[UIButton alloc]initWithFrame:CGRectMake(120, 120, 80, 30)];
[button2 addTarget:self action:@selector(button2Click:) forControlEvents:UIControlEventTouchUpInside];
button2.backgroundColor = [UIColor yellowColor];
[button2 setTitle:@"Stop" forState:UIControlStateNormal];
[self.view addSubview:button2];

// Do any additional setup after loading the view, typically from a nib.


- (void)didReceiveMemoryWarning 
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.


-(void)button2Click : (id)sender 

if (counter == 0) 

    [self.avAudioPlayer stop];

if (counter == 1) 

    [self.avAudioPlayer2 stop];



counter ++;

 

-(void)button1Click : (id)sender 

MPMediaPickerController *mediaPicker = [[MPMediaPickerController alloc] initWithMediaTypes: MPMediaTypeMusic];

mediaPicker.delegate = self;
mediaPicker.allowsPickingMultipleItems = YES;
mediaPicker.prompt = @"Select songs to play";
mediaPicker.showsCloudItems = NO;

[self presentViewController:mediaPicker animated:YES completion:nil];



-(void)mediaPicker:(MPMediaPickerController *)mediaPicker didPickMediaItems:(MPMediaItemCollection *)mediaItemCollection 

  [self dismissViewControllerAnimated:YES completion:nil];


MPMediaItem *item = [[mediaItemCollection items]objectAtIndex:0];
NSURL *myURL = [item valueForProperty:MPMediaItemPropertyAssetURL];


NSError *err1;


self.avAudioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:myURL error:&err1];


if (err1) 

    NSLog(@"@err1 : %@",[err1 localizedDescription]);




[self.avAudioPlayer play];


if ([mediaItemCollection items].count >1) 

    MPMediaItem *item2 = [[mediaItemCollection items]objectAtIndex:1];
    NSURL *myURL2 = [item2 valueForProperty:MPMediaItemPropertyAssetURL];
    NSError *err2;
    self.avAudioPlayer2 = [[AVAudioPlayer alloc]initWithContentsOfURL:myURL2 error:&err2];
    if (err2) 
        NSLog(@"err2 : %@",[err2 localizedDescription]);
    
    [self.avAudioPlayer2 play];



 // NSLog(@"mediaitemCollection : %@",[mediaItemCollection items]);




-(void)mediaPickerDidCancel:(MPMediaPickerController *)mediaPicker 

[self dismissViewControllerAnimated:YES completion:nil ];



@end

点击播放按钮并选择两个音乐文件,因为我们将allowsPickingMultipleItems 设置为YES

它在我的 ipad 上运行良好。如果需要,请快速转换它。我认为这不是一项艰巨的任务。

希望这能解决您的问题。 :)

【讨论】:

感谢您的链接,但有什么我可以快速查看的吗? 我已经更新了我的答案。它有一个链接可以快速检查它是否对您有帮助。 我尝试将这两行代码添加到我的每个 if 语句中,但它似乎不起作用。你知道我怎么能让这个工作吗?试试 AVAudiosession.sharedInstance().setActive(true) 试试 AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayAndRecord, withOptions: AVAudioSessionCategoryOptions.MixWithOthers) 你只需要制作两个不同的播放器,并且两个播放器都应该有不同的声音 url。检查上面的链接并相应地重建您的代码。我已经用很少的代码更新了我的答案,希望它可以帮助你。 我收到一条错误,它说参数标签与任何可用的重载都不匹配。 if let newPlayer = AVAudioPlayer(contentsOfURL:url, error:&error)

以上是关于如何让我的两个音频播放器同时播放两首不同的歌曲?的主要内容,如果未能解决你的问题,请参考以下文章

如何在 python 上同时播放两个不同的歌曲文件?

关于重叠歌曲的问题?

我们如何让 NSTimer 在 iOS 中为我​​的音频播放器在后台运行

如何同步2个音频文件?另一个的录音版本在哪里?

同时播放两个 AVPlayer 音频文件时出现音频故障

在 jQuery 中“转换”具有多个音轨的音频播放器